C <stdio.h> - ferror() Function
The C <stdio.h> ferror() function is used to check if the error indicator associated with the file stream is set. It returns a non-zero value if it is set, else returns 0.
The error indicator are generally set by a previous failed operation on the stream, and gets cleared by calling function like clearerr, rewind or freopen.
Syntax
int ferror ( FILE * stream );
Parameters
stream |
Specify a pointer to a FILE object that specifies the stream. |
Return Value
Returns non-zero value if the error indicator associated with the file stream is set, else returns 0.
Example:
Lets assume that we have a file called test.txt. In the example below, file is opened in read-only mode. The program tries to write a character in this file. As the file is opened in read-only mode, an error is generated which is detected by ferror() function.
#include <stdio.h> int main (){ //open the file in read mode FILE *pFile = fopen("test.txt", "r"); //write a character in the file fputc('A', pFile); //error is detected if(ferror(pFile)) printf("Some error has occurred."); //close the file fclose(pFile); return 0; }
The output of the above code will be:
Some error has occurred.
❮ C <stdio.h> Library