clearerr C Library Function

The function void clearerr(FILE *stream); clears the error and the eof indicators of given stream. If an Input/Output operation fails either because the end of the file has been reached or because of an error, it causes the internal indicators of the stream to be set. A call to clearerr function clears the state of these indicators.

Function prototype of clearerr

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

Return value of clearerr

NONE

C program using clearerr function

The following program shows the use of clearerr function to clear internal error indicators of a stream.

clearerr 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");
   /* trying to write on a read only file, 
      It will causes an I/O error */
   fputc('A', file);
   if(ferror(file))
   {
      printf("Error in writing in file\n");
      /* Clearing error indicators */
      clearerr (file);
   }
   /* trying to read from an empty file */
   fgetc(file);
   if(ferror(file))
   {
      printf("Error in reading from file\n");
      clearerr (file);
   }
   fclose(file);
    
   return(0);
}

Output

Error in writing in file
Error in reading from file