DEV Community

Jesse Phillips
Jesse Phillips

Posted on • Edited on

4

File Path Handling in D

Working with file paths is very annoying, especially on Windows where it supports both separators most of the time.

Aside from deciding which slash to use there are a couple of areas to consider.

  • Home directory
  • Relative vs absolute

D provides quick work of these.

std.path

import std.path;
buildNormalizedPath("foo/bar/../peas"
            .absolutePath.expandTilde);
Enter fullscreen mode Exit fullscreen mode

However trying to build a path by adding slash separators is not the best choice for building a path from variables.

auto a = "foo";
auto b = "bar";

assert([a, b].joiner("/").equal(a.buildPath(b)));
Enter fullscreen mode Exit fullscreen mode

And further work can be done on extensions.

assert("file.ext".extension == ".ext");
assert("file.ext".setExtension("gif") == "file.gif");
assert("file.ext".stripExtension == "file");
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️