Why is this C code buggy?

心不动则不痛 提交于 2019-11-28 12:43:58

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);

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!