Open In App

EOF, getc() and feof() in C

Last Updated : 27 May, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

In this article, we will discuss the EOF, getc() function and feof() function in C.

What is EOF?

In C, EOF is a constant macro defined in the <stdlib.h> header file that is used to denote the end of the file in C file handling. It is used by various file reading functions such as fread(), gets(), getc(), etc.

The value of EOF is implementation-defined, but generally is -1.

getc() Function

The getc() function is used to read a single character from the given file stream. It is implemented as a macro in <stdio.h> header file.

Syntax

C
getc(fptr);

Parameters

  • fptr: It is a pointer to a file stream to read the data from.

Return Value

  • It returns the character read from the file stream.
  • If some error occurs or the End-Of-File is reached, it returns EOF.

feof() Function

The feof() function is used to check whether the file pointer to a stream is pointing to the end of the file or not. It returns a non-zero value if the end is reached, otherwise, it returns 0.

Syntax

C
feof(fptr);

Parameters

  • fptr: Pointer to a file stream to read the data from.

Return Value

  • Returns a non-zero value (usually 1) if the end of the file is reached.
  • Otherwise, it returns 0.

Why feof() is needed?

getc() returns the End of File (EOF) when the end of the file is reached. getc() also returns EOF when it fails. So, only comparing the value returned by getc() with EOF is not sufficient to check for the actual end of the file. To solve this problem, C provides feof().

Example:

C++
#include <stdio.h>

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

    // Try to read a character using getc()
    ch = getc(fptr);
  
  	// Handle the EOF return value
    if (ch == EOF)
        printf("End of File or Unable to Read");
    else
        printf("Read Character: %c", ch);
  
    fclose(fptr);
    return 0;
}

Output
End of File or Unable to Read

In the above program, the getc() function should be unable to read as the file is opened in the write mode only. But it still returns EOF because of which it becomes difficult to find the source of error. Here, the feof() function can be specifically used to check for End of File.

C
#include <stdio.h>

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

    // Try to read a character using getc()
    ch = getc(fptr);
  
  	// Handle the EOF return value
    if (ch == EOF) {
      
      	// Check if the end of file is reached
      	// or just getc() is unable to read
      	if (feof(fptr) == EOF)
        	printf("End of File");
      else
        	printf("Unable to Read");
    }
    else
        printf("Read Character: %c", ch);
  
    fclose(fptr);
    return 0;
}

Output
Unable to Read

Next Article
Article Tags :

Similar Reads