Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What events can cause ferror to return non-zero?

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?

like image 731
Praxeolitic Avatar asked Dec 31 '14 06:12

Praxeolitic


1 Answers

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 (see ferror(3)) is set, and errno 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. greping for that constant will show you all of the places it is set/cleared.

like image 85
Jonathon Reinhart Avatar answered Sep 29 '22 19:09

Jonathon Reinhart