If successful, fgets() returns a pointer to the string buffer.
If unsuccessful, fgets() returns NULL to indicate failure.
If n is less than or equal to 0, it indicates a domain error; errno is set to EDOM to indicate the cause of the failure.
When n equals 1, it indicates a valid result. It means that the string buffer has only room for the NULL terminator; nothing is physically read from the file. (Such an operation is still considered a read operation, so it cannot immediately follow a write operation unless there is an intervening flush or reposition operation first.)
If n is greater than 1, fgets() will only fail if an I/O error occurs or if EOF is reached, and no data is read from the file.
The ferror() and feof() functions are used to distinguish between a read error and an EOF. Note that EOF is only reached when an attempt is made to read “past” the last byte of data. Reading up to and including the last byte of data does not turn on the EOF indicator.
If EOF is reached after data has already been read into the string buffer, fgets() returns a pointer to the string buffer to indicate success. A subsequent call would result in NULL being returned since EOF would be reached without any data being read.
This example gets a line of input from a data stream.
It reads no more than MAX_LEN - 1 characters, or up
to a new-line character, from the stream.
#define MAX_LEN 100
char line[MAX_LEN], *result;
stream = fopen("myfile.dat","r"
if ((result = fgets(line,MAX_LEN,stream)) != NULL)
printf("The string is %s\n", result);