Question

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)
Was it helpful?

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.

OTHER TIPS

fstat is to be used with a file descriptor obtained via the open call. Its main feature is to get information on already opened file descriptors instead of reopening.

You can also use fstat with FILE handlers like so (error handling omitted):

FILE *fp = fopen("/path/to/file", "r");
struct stat st;
fstat(fileno(fp), &st);

If you have a file descriptor, you do not necessarily know the path (e.g. when the file was opened by some other part of your application).

If you know the path, you do not need to call open to get a file descriptor just for the purpose of calling fstat.

If you look at man fstat, you will see the following:

fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor fd.

To expand a little bit, you would use fstat if you happened to have a file descriptor instead of a file path.

With respect to information provided by the function, they are literally identical, as you can see from the above quote.

If you only have a file descriptor to a file (but you may not know its path), then you could use fstat(); if you only have a path to a file, then you could use stat() directly, no need to open it first.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top