Upon looking at the ISO C11 standard for fgets
§7.21.7.2, 3, the return value is stated regarding the synopsis code:
#include <stdio.h>
char *fgets(char* restrict s, int n, FILE* restrict stream);
The fgets function returns s if successful. If end-of-file is encountered and no characters have been read into the array, the contents of the array remain unchanged and a null pointer is returned. If a read error occurs during the operation, the array contents are indeterminate and a null pointer is returned.
The standard says that a null pointer is returned for either an end-of-file and no characters have been read in or a read error occurs. My question is, just from fgets
, and the returned null pointer, is there a way to distinguish which of the two cases caused the error?
ferror()
. – Mungovanfeof()
andferror()
are designed for that. Be aware thatwhile (!feof(file))
is always wrong. – Nickens