cfilesystem-callsstatfstat

What are the advantages of using fstat() vs stat()?


If I have an open file with a known file descriptor, what are the advantages of using fstat(), versus stat()? Why isn't there only one function?

int fstat(int fildes, struct stat *buf)

int stat(const char *path, struct stat *buf)

Solution

  • As noted, stat() works on filenames, while fstat() works on file descriptors.

    Why have two functions for that?

    One factor is likely to be convenience. It's just nice to be able to fstat() a file descriptor that you obtained from other parts of your code, without having to pass the filename too.

    The major reason is security, though. If you first stat() the file and then open() it, there is a small window of time in between where the file could have been modified (or had its permissions changed, etc) or replaced with a symlink.

    fstat() avoids that problem. You first open() the file, then the file can't be swapped out beneath your feet any more. Then you fstat() and you can be sure that you have the right file.