Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
communitycreator

How to use clearerr() in C++

Arslan Bajwa

In C++, we can use the clearerr() function to reset error flags and end-of-file (EOF) indicators for a given file stream.

Syntax

void clearerr(FILE* stream);

stream represents the file stream that resets the error flags and EOF indicators. It is of FILE type.

Return value

It returns None.

Required header

<cstdlib>

Code

//Including headers
#include <cstdlib>
#include <iostream>
using namespace std;

int main() {
  //Creating file pointer
  FILE* fp = fopen("file.txt","r");

  if (fp == NULL){
    perror ("Error opening file");
  }
  else {
    fputc ('a',fp);
    if (ferror (fp)) {
      printf ("Error Writing to file.txt\n");
     
      //reset error flags
      clearerr (fp);
    }
    //Closing file pointer
    fclose (fp);
  }

   return 0;
}

Output

Error Writing to file.txt

RELATED TAGS

c++
communitycreator
RELATED COURSES

View all Courses

Keep Exploring