What is ferror() in C?

In C, the ferror() function checks if there is an error in the given stream.

Declaration

The declaration of ferror() is as follows:

int ferror(FILE* fptr);

Parameter

  • fptr: Pointer to the file stream we want to check for errors.

Return value

The ferror() function returns a non-zero value if there is an error associated with fptr. If there is no error associated with fptr, the function returns zero.

Example

Consider the code snippet below, which demonstrates the use of ferror():

main.c
ferrorExample.txt
#include <stdio.h>
int main()
{
FILE * fPointer;
fPointer = fopen("ferrorExample.txt","r"); //opening file
char buff[100]; //buffer
fgets(buff, 100, fPointer);
if(ferror(fPointer)) {
printf("Error reading from the file!\n");
}
else {
printf("file content: %s \n", buff);
}
fclose(fPointer);
fPointer = fopen("ferrorExample.txt","w");
fgets(buff, 100, fPointer);
if(ferror(fPointer)) {
printf("Error reading from the file!\n");
}
else {
printf("file content: %s \n", buff);
}
fclose(fPointer);
return 0;
}

Explanation

  • lines 6-19: The fopen() function is used in line 6 to open a file in read mode. The content of the file is read in buff using fgets(). The content of the file is read successfully. ferror() then returns 0 and the if condition in line 12 is not satisfied. Finally, the file content is printed on the screen.

  • lines 21-32: The fopen() function is used in line 21 to open a file in write mode. fgets() attempts to read the content of the file. This is unsuccessful. The error is given using ferror() as read operation is applied to the file opened in write mode. ferror() then returns non-zero value, the if condition in line 25 is satisfied, and an error message is printed on the screen.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved