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

www.i‮tfig‬idea.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 feof(), which checks if the end-of-file indicator has been set for a given file stream.

The feof() function takes one argument:

int feof(FILE *stream);

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

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

Here's an example of how to use feof() to check for the end-of-file 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 (feof(fp)) {
        printf("End of file reached.\n");
    } else {
        printf("Error reading file.\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 feof() function is called to check if the end-of-file indicator has been set. If it has, the message "End of file reached." is printed to the console. Otherwise, the message "Error reading file." is printed.