Skip to contentSkip to conversation

feof fails

DISCUSSION Christian Stalp 3 participants 3 messages Sep 15, 2004

lore
Share & tools
lore
#0 lore raw

Hello together,
I have a simple problem. I opened a file with fopen and read from the file with:
while ( !feof( infile ) )
{
fgets( buffer, BUFFER_SIZE, infile );
new_number = atoi ( buffer );
.....

The file is filled withe a stack of numbers, 7 charakters and each is terminated by an '\n'.

My problem now is, that the last number is been read twice. What is the problem?

Gruss Christian

Signature · 13 lines
Christian Stalp

Institut für Medizinische Biometrie, Epidemiologie und Informatik (IMBEI)
Obere Zahlbacher Straße 69
55131 Mainz
Tel.: 06131/ 17-6852

E-Mail: [email protected]
Internet: www.imbei.de
-
To unsubscribe from this list: send the line "unsubscribe linux-c-programming" in
the body of a message to [email protected]
More majordomo info at  http://vger.kernel.org/majordomo-info.html
#1 lore raw

hi,
Check whether u have put a \n at the end of last character.. u might have missed it.

Pankaj

Quoted 16 lines · Christian Stalp

Hello together,
I have a simple problem. I opened a file with fopen and read from the file with:
while ( !feof( infile ) )

 {
   fgets( buffer, BUFFER_SIZE, infile );
   new_number = atoi ( buffer );

......

The file is filled withe a stack of numbers, 7 charakters and each is terminated by an '\n'.

My problem now is, that the last number is been read twice. What is the problem?

Gruss Christian

#2 lore raw
In reply to Christian Stalp

"Christian Stalp" <[email protected]> wrote in message news:[email protected]...
Hello together,
I have a simple problem. I opened a file with fopen and read from the file with:
while ( !feof( infile ) )
{
fgets( buffer, BUFFER_SIZE, infile );
new_number = atoi ( buffer );
.....

The end of file condition is detected when trying to read from the file and failing.
Thus feof(infile) doesn't return non zero until after fgets fails at least once.
You should test fgets return value to detect end of file.
The reason the last number is read twice is that your particular implementation of fgets doesn't modify buffer upon end of file, it just returns NULL, which you don't check before parsing the contents of the buffer.

try this:

while (fgets(buffer, BUFFER_SIZE, infile)) {
    new_number = atoi(buffer);
    ...
}

simpler and better !

Chqrlie.

PS: wether the file is terminated with a newline or not is irrelevant to this question.