Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does stdio always set errno?

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++?

like image 377
Adrian Ratnapala Avatar asked May 20 '12 08:05

Adrian Ratnapala


1 Answers

The C Standard itself does not require much use of errno WRT to stdio functions; it specifies ferror() but says of it only that

7.13.10.3 The ferror function The ferror function tests the error indicator for the stream pointed to by stream. The ferror function returns nonzero if and only if the error indicator is set for stream.

from 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.

like image 90
CodeClown42 Avatar answered Sep 28 '22 13:09

CodeClown42