Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C library function - feof()

C library function - feof()

C Standard Library - <stdio.h> C Standard Library -

feof() is used to detect whether a file has been read to the end.

You can think of it as an 'end detector' - after reading each part of the content, ask it: 'Have we reached the end?'


Description

C library function int feof(FILE *stream) tests the end-of-file indicator of the given stream.

Two new concepts appear here; let us explain them separately:

A stream (stream) is C's abstraction for input and output. Whether it is a file on the hard disk, keyboard input, or network data, in C they are all uniformly treated as a 'stream'. You can imagine a stream as a water pipe, with data flowing from one end to the other.

The end-of-file indicator (EOF flag) is a status flag built into each file stream. It is like a bookmark that automatically flips to the 'read complete' page when the file content has been fully read.

feof()'s role is to check this bookmark - if it shows 'read complete', feof() returns a nonzero value. If the bookmark still says 'not finished', feof() returns 0.


Declaration

The following is the declaration of the feof() function, with each part explained:



int feof(FILE *stream)

int is the return type - feof() returns an integer; nonzero means the end has been reached, 0 means it has not.

FILE *stream is the parameter - you need to pass a file pointer (the pointer returned by fopen() when opening a file), telling feof() which file stream to check.


Parameters

feof() takes one argument:

Parameters Type Description
stream FILE * A file pointer, returned by the fopen() function, pointing to the open file to be checked

Return Value

The return values are described below:

Return Value Meaning
Non-zero values The file has been read to the end, with no more content to read
0 The file has not been fully read and can continue to be read

Key point: feof() returns a nonzero value only 'after an attempt has been made to read past the end of the file'. If you have just read the last character but have not attempted to read further, feof() still returns 0. This timing issue is explained in detail in the next section.


Example

The following example demonstrates the correct use of the feof() function.

The program reads the file content character by character, using feof() to check whether the end has been reached after each character.

Example

#include

int

main

(

)

{

   

// FILE * is the file pointer type, used to point to an open file

   FILE

fp

;

   

// fgetc() returns int instead of char, because it may need to return EOF (-1)

   

int

c

;

   

// fopen() opens a file, and "r" means read-only mode (read)

   fp

=

fopen

(

"file.txt"

,

"r"

)

;

   

// If the file does not exist or there is no permission, fopen() returns NULL

   

if

(

fp

==

NULL

)

   

{

     

// perror() prints a system error message to help locate the problem

     

perror

(

"Error opening file"

)

;

     

return

(

1

)

;

   

}

   

// Using an infinite loop with an internal check

   

// This ensures 'read first, then judge', avoiding reading extra content

   

while

(

1

)

   

{

     

// Step 1: read one character from the file

      c

=

fgetc

(

fp

)

;

     

// Step 2: immediately use feof() after reading to check whether the end has been reached

     

if

(

feof

(

fp

)

)

     

{

         

// Reached the end, break out of the loop, and do not process c

         

break

;

     

}

     

// Step 3: only after confirming the end was not reached, use the value of c

     

printf

(

"%c"

,

c

)

;

   

}

   

// fclose() closes the file and releases system resources

   

fclose

(

fp

)

;

   

return

(

0

)

;

}

Suppose we have a text file file.txt with the following content:



这里是 runoob.com

Compile and run the program above; the output is:



这里是 runoob.com

The program correctly printed the entire content of the file, without any extra garbled characters.


Common mistake: why feof() cannot be placed in the loop condition

Many beginners write the following, which looks more concise but is actually wrong:

Incorrect Example

#include

int

main

(

)

{

   FILE

fp

;

   

int

c

;

   fp

=

fopen

(

"file.txt"

,

"r"

)

;

   

if

(

fp

==

NULL

)

   

{

     

perror

(

"Error opening file"

)

;

     

return

(

1

)

;

   

}

   

// Wrong: using feof() as the entry condition of the loop

   

while

(

!

feof

(

fp

)

)

   

{

      c

=

fgetc

(

fp

)

;

     

printf

(

"%c"

,

c

)

;

   

}

   

fclose

(

fp

)

;

   

return

(

0

)

;

}

The output of this wrong version will be:



这里是 runoob.com

There is an extra garbled character at the end. Why? Let us trace the loop execution round by round:

Loop round Loop entry feof() fgetc() reads printf() outputs Description
Round 1 Returns 0 (not read yet) 'zhe' zhe Normal
Round 2 Returns 0 (not at the end yet) 'li' li Normal
... ... ... ... Middle characters output normally
Last round Returns 0 (not at the end yet) 'm' m The last normal character
An extra round Returns 0 (note! at this point 'm' has just been read, and feof does not yet know the end has been reached) EOF (-1) (garbled) bug! read one extra time

The root of the problem is: when you have just finished reading 'm' (the last character of the file), feof() still returns 0.

It must wait until you 'try to read once more' and find there is no more content to read, then it flips the internal flag to 'ended'.

So the form while(!feof(fp)) makes the loop run one extra round. In that extra round, fgetc() returns EOF (-1), and printf tries to print -1 as a character, producing garbled output.

Remember in one sentence:feof() is an 'after-the-fact report', not an 'advance warning'. It answers 'did the last read hit the end?', not 'will the next read hit the end?'. So never use feof() as the entry condition of a loop.

The correct pattern is the one in the earlier example - read first, then judge, and only use the content after confirming it is safe.


When to use feof()

feof() is mainly used in the following two scenarios:

Scenario Usage Example
Reading a file in a loop Read first, then judge (recommended) while(1) { c = fgetc(fp); if(feof(fp)) break; ... }
Troubleshooting read errors Distinguishing 'normal end' from 'read error' if(feof(fp)) { /* read normally to the end / } else if(ferror(fp)) { / read error */ }

In the second scenario, fgetc() returning EOF has two possibilities: the file was really fully read (judged with feof()), or an error occurred during reading (judged with ferror()). The two need to be handled differently.

C Standard Library - <stdio.h> C Standard Library -