Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
791 views
in Technique[技术] by (71.8m points)

file io - Why is this C code buggy?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'.
", 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'.
", mychar);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...