C++ ferror()

The ferror() function in C++ checks for error in the given stream.

ferror() prototype

int ferror(FILE* stream);

The ferror() function takes a file stream as argument and returns an integer value which specifies if the file stream consists of errors or not.

It is defined in <cstdio> header file.

ferror() Parameters

stream: The file stream who error is to be checked.

ferror() Return value

The ferror() function returns nonzero if the file stream has errors, zero otherwise.

Example: How ferror() function works

#include <iostream>
#include <cstdio>

using namespace std;

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

When you run the program, the output will be:

Can't read from file