Return value of fgets()

The documentation for fgets() does not say what you think it does:

From my manpage

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading
stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte (‘\0‘) is stored
after the last character in the buffer.

And later

gets() and fgets() return s on success, and NULL on error or when end of file occurs while no characters have been read.

I don’t read that as saying an EOF will be treated as an error condition and return NULL. Indeed it says a NULL would only occur where EOF occurs when no characters have been read.

The POSIX standard (which defers to the less accessible C standard) is here: http://pubs.opengroup.org/onlinepubs/009695399/functions/fgets.html and states:

Upon successful completion, fgets() shall return s. If the stream is at end-of-file, the end-of-file indicator for the stream shall be set and fgets() shall return a null pointer. If a read error occurs, the error indicator for the stream shall be set, fgets() shall return a null pointer, and shall set errno to indicate the error.

This clearly indicates it’s only going to return a NULL if it’s actually at EOF when called, i.e. if any bytes are read, it won’t return NULL.

Leave a Comment