2

In many cases I have seen an fstat call performed directly after the file descriptor has been assigned from a call to open:

fd = open(file, flags, mode);
fstat_result = fstat(fd, &stat_log);

Does fstat behave any differently if one has already performed a call to read first?

fd = open(file, flags, mode);
read_result = read(fd, buffer, buffersize)
fstat_result = fstat(fd, &stat_log);

And by "behave differently" I mean: Is the return value of fstat, or anything in the "struct stat" buffer output different in that scenario?

Do any of the size related members of stat_log now represent the size of the file remaining to be read?

If I have already read to the end of the file, will performing a call to fstat thereafter result in a failure? (fstat returning -1)

This fstat document doesn't seem to indicate any need for the file descriptor to reference a file that has not been read from yet. Have you found anything to indicate otherwise?

dtmland
  • 2,136
  • 4
  • 22
  • 45

1 Answers1

4

You can read from a file after opening it but before an fstat. The only thing that will change is any of the attributes that change as a result of that read. The only candidate would be atime, which would be the time of the read, which might be later than the time of the open.

abligh
  • 24,573
  • 4
  • 47
  • 84
  • Thanks for the repsone, however, I'm confused by your first statement. Are you saying I can't fstat after I have performed a read? Other than that, you are saying the only member that will be different is the atime member? – dtmland Mar 07 '14 at 18:22
  • 1
    You can call `fstat(2)` whenever you like. It will return the *current* data on the file, which might obviously change due to what your program (or even others) do to it. – vonbrand Mar 07 '14 at 18:28
  • As @vonbrand says, you can call `fstat` when ever you like (well, technically any time after the `open` but before the `close`), however, note that things you do to the file in the mean time may change the result. `read` will change very little, nothing except the `atime` as far as I know. Obviously writing it might change (e.g.) its size. – abligh Mar 07 '14 at 18:31
  • read might change more if it's a character-special device, but for an ordinary file, yeah, atime should be about it. – user3303729 Mar 07 '14 at 18:40
  • Assuming no one else is writing to the file - If the result of "read_result" above is greater than zero - then directly after when fstat is called - the st_size member should never report zero, correct? – dtmland Mar 07 '14 at 18:44
  • 1
    @dtmland for a normal file, yes, if no one else is writing it (including truncating it), `read` returning greater than zero would indicate it is non-zero in length. However, for things that aren't files, that wouldn't be the case. If it's a named pipe for instance, I believe `st_size` will always be zero, even though `read` will happily return a number greater than zero. – abligh Mar 07 '14 at 19:07