Use ferror()
rather than errno
to check whether an error has occurred on a file stream (after a long string of stdio
calls, for example). The ferror()
function tests the error indicator for a specified stream and returns nonzero if and only if the error indicator is set for the stream.
Non-Compliant Coding Example
Many implementations of the stdio
package adjust their behavior slightly if stdout
is a terminal. To make the determination, these implementations perform some operation that happens to fail fails (with ENOTTY
) if stdout
is not a terminal. Although the output operation goes on to complete successfully, errno
still contains ENOTTY
. This behavior can be mildly confusing, but it is not strictly incorrect, because it is only meaningful for a program to inspect the contents of errno after an error has been reported. ( More precisely, errno
is only meaningful after a library function that sets errno
on error has returned an error code.)
Code Block | ||
---|---|---|
| ||
errno = 0; printf("This\n"); printf("is\n"); printf("a\n"); printf("test.\n"); if (errno != 0) { fprintf(stderr, "printf failed: %s\n", strerror(errno)); } |
...