C clearerr()

In C programming, clearerr() clears the end-of-file and error indicators for the given stream.

The clearerr() function is defined in <stdio.h> header file.

C clearerr() Prototype

void clearerr(FILE *stream);

Function clearerr() takes one parameter which is the pointer to a FILE object that identifies the stream.

The function doesn't return any value.

Example: C clearerr() function

#include <stdio.h>

int main ()
{
  FILE * pFile;
  pFile = fopen("myfile.txt","r");

  if (pFile == NULL) perror ("Error opening file");
  else {
    fputc('x', pFile);

    if(ferror(pFile)) 
    {
      printf("Error Writing to myfile.txt\n");
      clearerr(pFile);
    }

    fgetc(pFile);

    if (!ferror(pFile))
      printf("No errors reading myfile.txt\n"); 

    fclose(pFile);
  }

  return 0;
}

Output

Error Writing to myfile.txt
No errors reading myfile.txt

This program opens an existing file called myfile.txt for reading.

Now, the function fputc() tries to write to the file. Since, writing is not allowed in reading mode, it causes an I/O error.

However, this error is cleared using clearerr(). So, when the next error check occurs in ferror() function, it displays that no errors were found.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges