EOF, getc() and feof() in C (original) (raw)

Last Updated : 9 Apr, 2026

Handling file input in C often involves EOF and functions like getc() and feof().

EOF

In C, EOF is a constant macro defined in the ****<stdio.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

getc(fptr);

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

**Return Value

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

feof(fptr);

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

**Return Value

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;

}

`