When a stdio stream encounters an error (but not EOF), the stream’s error indicator will be set so that ferror() will return nonzero. I have always assumed that more information is available in errno. But how do I know this?
Documentation for some functions [e.g. man fopen under Linux] says that errno will also be set. However man fgets doesn’t mention errno at all. The glibc info pages are reassuring:
In addition to setting the error indicator associated with the
stream, the functions that operate on streams also set `errno’ in the
same way as the corresponding low-level functions that operate on file
descriptors.
But I have no idea how strong this guarantee is. Is it required by the C standard? What happens in Visual C/C++?
The C Standard itself does not require much use of errno WRT to
stdiofunctions; it specifiesferror()but says of it only thatfrom the C99 Draft: http://www.vmunix.com/~gabor/c/draft.html. Any actual error codes used are, for the most part, implementation defined.
However, the GNU C library on linux also conforms to POSIX specifications:
http://pubs.opengroup.org/onlinepubs/9699919799/toc.htm
Which are much more well defined in this context. For example, if you look at the page for
fopen:http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html
You’ll see a lot of detailed information, including specific errno codes, under Errors.
Again, the GNU C library used on virtually all normal linux systems is POSIX compliant, so you can count on that information ;). Those (online) POSIX man pages are also generally more detailed than the standard linux system man pages (read both).
WRT to file operations on other (non-POSIX) platforms, they will have their own implementations. Unfortunately, stuff like that is not transparently portable in standard C. C++ streams do have more standardized error handling, though.