Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 946
Rasteril Avatar asked Apr 19 '14 11:04

Rasteril


2 Answers

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.

like image 158
Christian Aichinger Avatar answered Sep 24 '22 19:09

Christian Aichinger


fstat is to be used with a file descriptor obtained via the open call.

That said, given a FILE *fp opened with fopen and struct stat st, you can use fstat like this : fstat(fileno(fp), &st);.

like image 28
Chnossos Avatar answered Sep 23 '22 19:09

Chnossos