C ferror() Function Tutorial

  • Post author:
  • Post category:C

In this section, we will learn what the ferror() function is and how it works in C.

C ferror() Function

Sometimes a program opens a file in read mode or write mode only and then attempts to do the opposite work!

For example, the file is opened in read mode and the program attempts to write content to that file or vice versa.

In such case, an error-indicator in the FILE-structure of the target file will be set, which means an error happened while attempting to do something on the file.

We can keep an eye on this indicator via the call to the `ferror()` function.

Note: make sure you include the `stdio.h` header file because this is the file that contains the prototype of the function.

C ferror() Function Syntax:

Here’s the prototype of the function:

int ferror(FILE *stream)

C ferror() Function Parameters

The function only takes one argument and that is the memory address assigned to the FILE-structure of the target file.

C ferror() Function Return Value

The returned value of this function is 0 if the indicator is not set and a non-zero value if the error-indicator is set.

Example: using ferror() function in C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {


    FILE *file = fopen("G:/fileOne.txt","r");

    if (file == NULL){
        printf("Could not open the file");
        exit(EXIT_FAILURE);

    }

    char c;
    putc('a',file);
    if (ferror(file)){
        printf("The error indicator of the FILE-Structure is set\n");
        printf("Now clearing the error via the call to clearer function \n");
        clearerr(file);
    }

    fclose(file);

    printf("\nDone\n");
    return 0;
}

Output:

The error indicator of the FILE-Structure is set

Now clearing the error via the call to clearer function

Done

Note: after an error-indicator is set, we can clear that error via the call to the `clearerr()` function. This function takes the address of the FILE-structure of the target file and resets the error-indicator in that file. (also the function returns nothing)

Leave a Reply