Ferror c – ferror C Library Function

Ferror c: The function int ferror(FILE *stream); checks the status of error indicator associated with the given stream. To get the exact nature of the error, we should use perror function. A call to clearerr, freopen or rewind clears the error indicator.

Function prototype of ferror

int ferror(FILE *stream);
  • stream : A pointer to a FILE object which identifies a stream.

Return value of ferror

This function returns zero if no error has occurred, otherwise a non-zero value in case of an error.

C program using ferror function

The following program shows the use of ferror function to handle I/O errors. Let us assume we have an empty file called “textFile.txt”. Below program opens “textFile.txt” in read-only mode but tries to write a character in it, which causes an error that is detected by ferror function.

ferror C Library Function

#include <stdio.h>
 
int main(){
   FILE *file;
   char ch;
   /* Opening an empty text file in read only mode*/
   file = fopen("textFile.txt", "r");
   /* It will causes an I/O error trying to write on it */
   fputc('A', file);
   if(ferror(file))
   {
      printf("Error: writing in a read only file\n");
      /*Clearing error indicators */
      clearerr (file);
   }
   fclose(file);
    
   return(0);
}

Output

Error: writing in a read only file