C programming stdio.h function - int ferror(FILE *stream)

https://w‮‬ww.theitroad.com

In C programming, the stdio.h header file provides a set of functions for performing input and output operations on streams of data. One of the functions in this header file is ferror(), which checks if an error indicator has been set for a given file stream.

The ferror() function takes one argument:

int ferror(FILE *stream);

The argument, stream, is a pointer to a FILE object that represents the file stream to be checked.

The ferror() function checks if an error indicator has been set for the specified file stream. If an error indicator is set, the function returns a non-zero value. Otherwise, it returns 0.

Here's an example of how to use ferror() to check for an error indicator on a file stream:

#include <stdio.h>

int main() {
    FILE *fp;
    int ch;

    fp = fopen("example.txt", "r");
    if (fp == NULL) {
        printf("Error opening file.\n");
        return 1;
    }

    /* Read characters from the file stream */
    while ((ch = fgetc(fp)) != EOF) {
        printf("%c", ch);
    }

    if (ferror(fp)) {
        printf("Error reading file.\n");
    } else {
        printf("End of file reached.\n");
    }

    fclose(fp);

    return 0;
}

In the above example, the fopen() function is used to open a file named "example.txt" in read mode. The fgetc() function is then used to read characters from the file stream, and print them to the console. After all the characters have been read, the ferror() function is called to check if an error indicator has been set. If it has, the message "Error reading file." is printed to the console. Otherwise, the message "End of file reached." is printed.