Question Details

No question body available.

Tags

c language-lawyer fgets

Answers (1)

May 23, 2026 Score: 5 Rep: 234,989 Quality: Medium Completeness: 80%

Consider the situation where fgets reaches EOF but did read something into s,

fgets will read up to sizeof(s)-1 bytes into s. If it reads less then that without reading a newline but at least 1 byte, then fgets will return s and the eof-of-file marker will be set, meaning that the call to feof is guaranteed to return true.

The fgets function is classified as a byte input function as defined in section 7.23.1p6 of the C23 draft standard. Section 7.23.3p11 further states:

The byte input functions read characters from the stream as if by successive calls to the fgetc function

And section 7.23.7p3 regarding the fgetc function states:

If the end-of-file indicator for the stream is set, or if the stream is at end-of-file, the end-of-file indicator for the stream is set and the fgetc function returns EOF.

This means that if fgets attempts to read past end-of-file then the end-of-file indicator would be set and feof will subsequently return true.

For example, if s is defined as char s[5] and there are 3 bytes left to read in the file, then s will contain those 3 bytes followed by a null byte and the end-of-file indicator will be set.

Note that reading up to eof-of-file without reading past it does not set the end-of-file marker. So in the above example, if there are either 4 bytes left to read in the file or less than 4 but the last byte is a newline, end-of-file is not set and the next call to fgets will return NULL and set the eof-of-file marker.