Search code examples
cfileioscanfeof

fscanf - How to know if EOF means end of file or reading/another error?


I have a question about I/O in C language, how can I make a difference to know if the lecture of my file has ended or if the data can't be read (or has a problem) as in the both cases, fscanf returns EOF ?


Solution

  • Don´t rely only on the return value of fscanf(), rely beside this one on feof() and ferror() after the call to fscanf():

    FILE* file;
    if((file == fopen("file.txt","r")) == NULL)
    {
        fprintf(stderr, "File could not be opened!");
        return EXIT_FAILURE;
    }
    
    char buf;
    
    /******************************************************************************/
    
    while(fscanf(file,"%c",buf) == 1) {     // checks if an error was happen, else 
                                            // iterate to catching characters.
       /* handling of read character */
    }
    
    if(ferror(file))                        // checks if an I/O error occurred.
    {
       // I/O error handling
       fprintf(stderr,"Input/Output error at reading file!");
       clearerr(file);
       // Further actions
    }
    else if(feof(file))                     // checks if the end of the file is reached.       
    {
       // end of file handling
       fprintf(stderr,"Reached End of File!");
       clearerr(file);
       // Further actions
    }
    
    /******************************************************************************/
    
    if(fclose(file) != 0)
    {
        fprintf(stderr, "File could not be closed properly!");
        return EXIT_FAILURE;
    }