I am tempted to use `std.fs.Dir.realpath()`

I want to accept a file path from the user via a cli option and write to it.

I want to be able to accept paths like:

./foo.bin
../foo.bin
foo.bin (same as ./foo.bin)
/home/Batman/downloads/foo.bin

and for it to “just work”.

I also found this issue

which is essentially “realpath considered harmful”, but I don’t really know why.

What should I do?

All of these work fine for all of the Dir APIs, so, for example:

std.fs.cwd().openFile("./foo.bin", .{});
std.fs.cwd().openFile("../foo.bin", .{});
std.fs.cwd().openFile("foo.bin", .{});
std.fs.cwd().openFile("/home/Batman/downloads/foo.bin", .{});

all work. The relative paths are resolved relative to the Dir, which in the examples above is std.fs.cwd(), but it could be another directory if you want:

var dir = try std.fs.cwd().openDir("path/to/dir", .{});
defer dir.close();

const file = try dir.openFile("can-be-relative-or-absolute.bin", .{});
defer file.close();

If you want more details, I’ve made some other relevant comments in the past

5 Likes