C clearerr()

The clearerr() function defined in the stdio.h header file. It helps to reset the End of File(EOF) indicator and the error flag associated with the stream pointed by the specified stream.

int fclose(FILE *stream); #where stream should be a file pointer


clearerr() Parameters: 

The clearerr() function takes a single parameter. Using the perror() function we can find out the exact nature of the error. The message displayed by the function is the actual error.

Parameter Description Required / Optional
stream the pointer to a FILE object that identifies the stream Required

clearerr() Return Value

If an invalid stream is passed the return value of clearerr() function should be -1 and set errno to EBADF.

Input Return Value
Invalid stream return -1

Examples of clearerr()

Example 1: Working of clearerr() function in C?

#include <stdio.h>

int main()
   FILE *pnt;
   char ch;

   pnt = fopen("file.txt", "w");

   ch = fgetc(pnt);
   if( ferror(pnt) ) {
      printf("Reading error from the file : file.txt\n");
   if( ferror(pnt) ) {
      printf("Reading error from the file : file.txt\n");



Reading error from the file "file.txt"

Example 2: How clearerr() works in C?

#include <stdio.h>

int main (){
   FILE * pnt;
  pnt = fopen("testfile.txt","r");
  if (pnt==NULL) perror ("Error in opening file");
  else {
    fputc ('x',pnt);
    if (ferror (pnt)) {
      printf ("Error in writing to testfile.txt\n");
      clearerr (pnt);
    fgetc (pnt);
    if (!ferror (pnt))
      printf ("No errors in reading testfile.txt\n"); 
    fclose (pnt);
  return 0;


Error in writing to testfile.txt
No errors in reading testfile.txt