为什么这个 C 代码有问题? [英] Why is this C code buggy?

查看:22
本文介绍了为什么这个 C 代码有问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于另一个问题Jerry Coffin 指出了以下几点:

On another question, Jerry Coffin pointed out the following:

它(可能)与您的问题并不真正相关,但是 while (!feof(fileptr)){ 几乎是一个有保证的错误.

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

我想我会开始一个单独的问题,因为该评论有点偏离主题.有人可以向我解释一下吗?这是我之前用直接 C 编写的第一个程序.

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.

推荐答案

此语句的原因是 feof 在到达文件末尾时仍然(最初)为 false -- 它只有在第一次尝试读取文件末尾失败后才变为真.

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.

因此

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

将处理过多的一个字符.

will process one char too many.

正确的方法是检查 fread(或您用来读取的任何函数)的返回值,或者在之后调用 feof 进行读取的函数.例如:

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

这篇关于为什么这个 C 代码有问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆