Does EOF set errno?

c, system-calls, unix

Solution

Use `ferror` and `feof` to distinguish between error and EOF. There's no general way to find out exactly what the error was, if there was an error, but you can tell that there was one.

Standard C `(f)gets` (and `(f)getc`) are not required to set `errno`, although a conforming library implementation can set `errno` to a non-zero value pretty much at will.

Posix does requires that `(f)get{c,s}` set `errno` on read errors, but that only helps you after you have determined that there was a read error (by calling `ferror`). It's also important to remember that library functions never set `errno` to 0, but may set `errno` to a non-zero value even if no error occurs. So you cannot test `errno` as a replacement for checking the error return of any library function, including `fgets`. And since end-of-file is not an error, `errno` will (probably) not be modified on EOF, so its value in that case is meaningless.

Problem

I always struggle with return values of system calls - they are just so inconsistent! Normally I check if they are NULL or -1 and then call `perror`. However, for `fgets`, the man page says: `gets()` and `fgets()` return s on success, and `NULL` on error or when end of file occurs while no characters have been read. which means the return value `NULL` is not necessarily an error - it can also be EOF. Is errno set when the end of file is reached? Can I still call `perror` in this case? If not, what is the common way to tell if the call returned an error versus EOF. I want to use `perror` with NULL string for errors and a custom string for EOF.

Original source

Related problems