C
Chris Torek
stat() works on paths not file descriptors. If you're alluding to race
conditions all file routines have them.
Not *all*: open() with O_CREAT|O_EXCL, for instance, does not.
Indeed, this is the *only* way to guarantee that a file that did
not exist before the call is created by the call and does exist
after the call.
Similarly, open() followed by fstat() avoids some (but not all)
races: in particular, the information you get with fstat() will
definitely refer to the underlying file, and the st_ino, st_dev,
and st_rdev fields should not change (of course the size, owner,
and permissions, for instance, could change).
BTW saying "stat" isn't portable is kinda moot since not all platforms
have files anyways.
While the latter is true, the former is an overstatement: there are
hosted systems that have "files" dealt with via fopen, but lack
the stat() family of calls (e.g., C on some Univac and IBM sysems).
But even Windows has "stat" like functionality. BSD, MacOs, Linuxes
have it too. So do UNIXes. So very likely using some stat function is
better than opening the file and doing some ftell crap.
Usually it is best to open() the file, then use fstat() if needed.
On many systems, this is essentially just as fast as using stat()
on the file, too; and if you intend to open it after getting the
result from stat(), open() followed by fstat() is faster -- often
significantly faster -- than stat() followed by open(). The reason
is that most of the work (and hence most of the time) goes to
translating path names, rather than dealing with the final on-media
entity representing the file. Doing stat(), then open(), runs the
slow code twice; doing open(), then fstat(), runs it only once.
(On vxWorks, stat() is in fact implemented as open() followed by
fstat() followed by close(). So here it is *definitely* more
efficient to open() first, then fstat().)