Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
ferror()
communitycreator

How to use ferror() in C++

Arslan Bajwa

In C++, we can use the ferror() function to check for errors in the input file stream. It returns a non-zero value if the error indicator is set.

Syntax

int ferror(FILE* stream);

stream

It represents a pointer to the file stream for which we need to check errors. It is of FILE* type.

Return value

  • 0: It returns 00 if the file stream does not have any errors.

  • Non-zero: It returns a non-zero value if errors are in the file stream.

Required headers

#include<cstdio>

Code

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

int main() {

   int ch;
   FILE* fp = fopen("file.txt","w");
    
   if(fp) {
      ch = getc(fp);
      if (ferror(fp))
         cout << "Can't read from file";
   }
   fclose (fp);
   return 0;
}

Output

Can't read from file

RELATED TAGS

c++
ferror()
communitycreator
RELATED COURSES

View all Courses

Keep Exploring