Correct way to handle file-or-directory

i have a simple command line program that accepts a path argument. if it is a file, it reads it to a string. if it is a directory, it iterates through it and recurses on the contained files.

what is the correct way to do this that is cross-platform and avoids TOCTOU errors? ErrorKind::IsADirectory seems to be nightly-only.

the unix way of doing this would be to open the path, do a stat to figure out if it is a dir or file, then call either read or readdir accordingly, but there doesn't seem to be an equivalent method on File

There is no way to avoid all TOCTOU-shaped failures when traversing a directory tree. For example, a file might be deleted between the time you read its name from the directory and the time you open the file. If you want to be robust against concurrent modifications, you have to treat errors like you would atomic compare-and-swap failures: “something changed, so try again with a new read” — not signs that you necessarily did anything wrong.

3 Likes

On Linux (I use Linux and don't know how it's on other operating systems), one of the ways to handle it is to open a file descriptor for the target object, and then call fstat() to see if it's a file or a directory (or some other object, like FIFO). Other operating systems likely provide something similar -- you should check the documentation.

cap-std lets you turn a File into a Dir. I plan on bringing some of that functionality into std, but that'll take time.

1 Like

yes, i literally talked about doing exactly this in the first comment.

what i'm looking for is a cross-platform abstraction for this

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.