File Paths in D Programming Language

The std.path module provides functions to parse and construct file paths in a way that is portable between operating systems; dir/file on Linux vs. dir\file on Windows, for example.

import std.stdio;
import std.path;
import std.string;

void main()
{
    // buildPath should be used to construct paths in a
    // portable way. It takes any number of arguments
    // and constructs a hierarchical path from them.
    string p = buildPath("dir1", "dir2", "filename");
    writeln("p: ", p);

    // You should always use buildPath instead of
    // concatenating '/'s or '\'s manually. In addition
    // to providing portability, buildPath will also
    // normalize paths by removing superfluous separators
    // and directory changes.
    writeln(buildPath("dir1//", "filename"));
    writeln(buildPath("dir1/../dir1", "filename"));

    // dirName and baseName can be used to split a path to the
    // directory and the file. There's no direct equivalent to
    // Split in D, but you can use both functions together.
    writeln("dirName(p): ", dirName(p));
    writeln("baseName(p): ", baseName(p));

    // We can check whether a path is absolute.
    writeln(isAbsolute("dir/file"));
    writeln(isAbsolute("/dir/file"));

    string filename = "config.json";

    // Some file names have extensions following a dot. We
    // can split the extension out of such names with extension.
    string ext = extension(filename);
    writeln(ext);

    // To find the file's name with the extension removed,
    // use stripExtension.
    writeln(stripExtension(filename));

    // relativePath finds a relative path between a base and a
    // target. It returns an empty string if the target cannot
    // be made relative to base.
    string rel = relativePath("a/b", "a/b/t/file");
    writeln(rel);

    rel = relativePath("a/b", "a/c/t/file");
    writeln(rel);
}

To run the program, save it as file_paths.d and use the D compiler (dmd) to compile and run:

$ dmd -run file_paths.d
p: dir1/dir2/filename
dir1/filename
dir1/filename
dirName(p): dir1/dir2
baseName(p): filename
false
true
.json
config
t/file
../c/t/file

This D code demonstrates the usage of file path manipulation functions provided by the std.path module. It covers joining paths, extracting directory and file names, checking for absolute paths, working with file extensions, and finding relative paths. The D standard library provides similar functionality to Go’s filepath package, making it easy to work with file paths in a cross-platform manner.