Search code examples
cfgets

how to differentiate between fgets reaching EOF and reaching error


I have a question about the fgets()

char *fgets(char *str, int strsize, FILE *stream);

fgets()' document says:

On success, the function returns the same str parameter. If the End-of-File is encountered and no characters have been read, the contents of str remain unchanged and a null pointer is returned.

If an error occurs, a null pointer is returned.

  1. How do you differentiate between above two situations - fgets reaching EOF(END OF FILE) & error whilst reading file?

  2. Also, when an error occurs whilst fgets reads file, does fgets keep track of whatever has been read up to that point in the str?

  3. How do you check if fgets immediately reaches EOF?


Solution

  • Referring your 1st question:

    How do you differentiate between above two situations - fgets reaching EOF(END OF FILE) & error whilst reading file?

    If fgets() returned NULL, call ferror() for the file pointer which just before had been used with the fgets() call, which returned NULL. If ferror() returns a non zero value, then fgets() failed, else it had reached the end-of-the file.

    Example:

    #include <stdlib.h>
    #include <stdio.h>
    #include <errno.h>
    
    #define LINE_LEN_MAX (42)
    
    int main(int argc, char ** argv)
    {
       if (1 >= argc)
       {
         errno = EINVAL;
         perror("main() failed");
         exit(EXIT_FAILURE);
       }
    
       {
         FILE * fp = fopen(argv[1], "r");
         if (NULL == fp)
         {
           perror("fopen() failed");
           exit(EXIT_FAILURE);
         }
    
         for (char line[LINE_LEN_MAX];
           NULL != fgets(line, LINE_LEN_MAX, fp);)
         {
           printf("%s", line);
         }
    
         if (0 != ferror(fp))
         {
           perror("fgets() failed");
           exit(EXIT_FAILURE);
         }
    
         fclose(fp);
       }
    
       return EXIT_SUCCESS;
     }
    

    The other to question can be answered straight forward from the docs:

    Question 3:

    How do you check if fgets immediately reaches EOF?

    Answer:

    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.

    Question 2:

    when an error occurs whilst fgets reads file, does fgets keep track of whatever has been read up to that point in the str?

    Answer:

    If a read error occurs during the operation, the array contents are indeterminate and a null pointer is returned.