Preferred idiom to test for a file's existence

i have an absolute path to a file (or directory)… what’s the best way to check whether the file actually exists???

i’ve seen a variety of suggestions after googling around, but they all seemed a little heavy-handed

1 Like

The access functions are meant for that, but if you intend to open them it’s better to use open functions and handle the error if the file/directory wasn’t found.

So, to check the existence of an absolute path use std.fs.accessAbsolute, but if your intention is to open it as well use:

  • std.fs.openFileAbsolute for files
  • std.fs.openDirAbsolute for directories
6 Likes

@tensorush is correct. Also good to keep in mind: if you intend to do any locking (using your file as a sort of semaphore), you never want to check for the file’s existence, and you always want to try creating the file with the appropriate flags, letting the creation fail when somebody else has the lock.

5 Likes

Just want to add that the Absolute suffixed std.fs functions should only be used when you know the path is absolute. If you just have some arbitrary path, you can do

try std.fs.cwd().access(path);

or openFile, openDir, etc (they all work with both relative and absolute paths). This issue is also slightly relevant.

5 Likes