Open In App

ferror() in C

Last Updated : 03 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C, ferror() is a built-in function used to check errors in files during file operations. It provides a simple way to do file operations without any interruption in your C program.

Syntax

ferror() is a standard library function defined in <stdio.h> file.

ferror(fptr)

Parameter:

  • Take as a file stream in parameter.

Return Value:

  • If the file has error, it returns a non-zero value.
  • Otherwise, it returns 0.

Note: To check error in file using ferror(), file must be open before it.

Examples of ferror()

The following examples demonstrate the use of ferror() in C programs.

Check Error When Writing Data

C
#include <stdio.h>

int main() {
    FILE *fptr = fopen("gfg.txt", "w");

    // Write data to the file
    fprintf(fptr, "Hello, GFG!");
    
  	// Check error after writing data into file
    if(ferror(fptr)==0)
        printf("Data written successfully.");
    fclose(fptr);
    return 0;
}

Output
Data written successfully.

Check Error When Read Data

C
#include <stdio.h>

int main() {
    FILE *fptr = fopen("gfg.txt", "w+");
    fprintf(fptr, "GeeksForGeeks!");
    
    rewind(fptr);
    
    char d[14]; 
    while (fscanf(fptr, "%s", d) != EOF)
    
  	// check error after reading data from file
    if(ferror(fptr)==0){
        for(int i=0; i<sizeof(d); i++){
            printf("%c", d[i]);
        }
        printf("\nNo error, Data read successfully");
    }
    fclose(fptr);
    return 0;
}

Output
GeeksForGeeks!
No error, Data read successfully

Next Article

Similar Reads