问题
What events can cause ferror()
to return non-zero and after what events should one check ferror()
?
http://www.cplusplus.com/reference/cstdio/ferror/
Opening, reading, closing?
Will the return value of ferror()
ever change spontaneously? E.g., if a program checks ferror(stream)
, takes a nap without interacting with the FILE
object associated with stream
, and then checks ferror(stream)
again, will the return value ever be different?
Is any of this mandated by standards?
回答1:
It is primarily errors returned from the underlying system calls (e.g. read
, write
, lseek
, close
) that will cause the stream's error bit to be set.
Many f___()
functions from stdio.h
indicate that if the end-of-file is reached, or an error occurs, ferror()
or feof()
will indicate why. fscanf, for example:
The value
EOF
is returned if the end of input is reached before either the first successful conversion or a matching failure occurs.EOF
is also returned if a read error occurs, in which case the error indicator for the stream (seeferror(3)
) is set, anderrno
is set indicate the error.
Functions from stdio.h
are synchronous - there's no background thread doing anything, so no, the error bit (returned from ferror()
) will never spontaneously change. It will only be affected by a call to libc by your application.
For the very curious, one could clone the GLibc Git repository (git://sourceware.org/git/glibc.git
) and have a look at the code itself.
ferror()
essentially just checks for the _IO_ERR_SEEN
bit in the file's _flags
field. grep
ing for that constant will show you all of the places it is set/cleared.
来源:https://stackoverflow.com/questions/27717132/what-events-can-cause-ferror-to-return-non-zero