Why is this C code buggy?
Asked Answered
G

3

3

On another question, Jerry Coffin pointed out the following:

It's (probably) not really related to your question, but while (!feof(fileptr)){ is pretty much a guaranteed bug.

I figured I would start a separate question since that comment is somewhat off-topic. Could someone explain this to me? This was the first program I've written in straight C before.

Getz answered 19/10, 2009 at 12:11 Comment(0)
T
8

The reason for this statement is that feof is still (initially) false when the end of the file has been reached -- it only becomes true after the first failed attempt to read past the end of the file.

Hence

char mychar;
while(!feof(fileptr))
{
    fread(&mychar, sizeof(char), 1, fileptr);
    fprintf(stderr, "The char is '%c'.\n", mychar);
}

will process one char too many.

The correct way is to check the return value of fread (or whatever function you're using to read) or, alternatively, to call feof after the function that does the reading. For example:

char mychar;
while(fread(&mychar, sizeof(char), 1, fileptr) > 0)
    fprintf(stderr, "The char is '%c'.\n", mychar);
Tesch answered 19/10, 2009 at 12:24 Comment(2)
nit: the problem is not that the loop reads one char too many, but that it writes one too many.Monroemonroy
The devil is in the details... I guess that's why we're programmers. ;) Edited to "process one char too many", since that's also a good description of what would happen in a real application.Tesch
O
5

Google finds this: http://www.drpaulcarter.com/cs/common-c-errors.php#4.2

It says "The author has yet to see any student use the feof() function correctly!"

To summarize, the C file functions like fread and fwrite return status values anyway which you <blink>should not ignore</blink>. Checking the value of feof is one of those bolting the stable door after the horse has already fled kind of things.

Obsecrate answered 19/10, 2009 at 12:20 Comment(4)
Give a short synopsis of the link in your answer. It makes your answer much more valuable to a search engine.Arizona
By some incredible coincidence, I was in the process of doing exactly that when I received your commented communication.Obsecrate
@Kinopiko - Alliteration is awesome.Getz
This is now the top hit on Google for "bolting the stable door after the horse has already fled", which isn't bad for something posted 18 minutes ago.Obsecrate
B
1

The C FAQ list has an answer along with answers to many other such frequently asked questions:

In C, end-of-file is only indicated after an input routine has tried to read, and failed.

Basseterre answered 19/10, 2009 at 15:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.