C++ Standard Library C++ STL Library

C++ <cstdio> - clearerr() Function



The C++ <cstdio> clearerr() function resets the error flags and the EOF indicator for the given file stream.

When a input/output function fails either because of an error or because the end of the file has been reached, one of these internal indicators may be set for the stream. The state of these indicators is cleared by calling clearerr() function, or by calling any of these functions: rewind(), fseek(), fsetpos() and freopen().

Syntax

void clearerr ( FILE * stream );

Parameters

stream Specify a pointer to a FILE object that specifies the stream.

Return Value

None.

Example:

Lets assume that we have a file called test.txt. This file contains following content:

This is a test file.
It contains dummy content.

In the example below, file is opened in read mode. When it is attempted to write a character in the file, it sets the error flag, which is cleared by calling clearerr() function. Therefore, when it is attempted to read the file, it shows no error.

#include <stdio.h>
 
int main (){
  //open the file in read mode
  FILE *pFile = fopen("test.txt", "r");
  
  //attempted to write a character in the file
  fputc ('x',pFile);

  //if error flags are set, display
  //message and clear all error flags
  if (ferror (pFile)) {
    printf("Error Writing to test.txt\n");
   clearerr (pFile);
  }

  //attempted to read first character from the file  
  fgetc (pFile);

  //if no error, display the message 
  if (!ferror (pFile))
    printf("No errors reading test.txt\n"); 
  
  //close the file
  fclose(pFile);

  return 0;
}

The output of the above code will be:

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

❮ C++ <cstdio> Library