有什么更好的办法来检查EOF和龟etc的误差()? [英] What is the better way to check EOF and error of fgetc()?

查看:153
本文介绍了有什么更好的办法来检查EOF和龟etc的误差()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直用这个办法

int c;
while ((c = fgetc(fp))!=EOF)
{
    printf("%c", c);
}

至于在我看来,更具有可读性和鲁棒性。但对于我的回答链接,<一个href=\"http://stackoverflow.com/questions/32640855/integer-variable-used-with-fgetc/32640939#comment53133141_32640939\">chux评论说,

如果(的feof(FP))比更强大的
     INT℃;而((C =龟etc(FP))!= EOF)

if ( feof(fp) ) is more robust than int c; while ((c = fgetc(fp))!=EOF)

    while(1)
    {
        c = fgetc(fp);
        if ( feof(fp) )
        {
            break ;
        }
        printf("%c", c);
    }

比第一版本更加健壮。所以,我应该用什么版本?请解释一下我为什么那个版本比较好。

is more robust than the first version. So what version should I use? Please explain me why that version is better.

修改

是,而(!的feof(文件))总是错了吗?有问为什么的feof()在控制回路总是错的。但检查的feof()中,如果以适当的方式条件永远是错的?解释是AP preciable。

In question Why is "while ( !feof (file) )" always wrong? there asked why feof() in control loop always wrong. But checking feof() in if condition in proper way is always wrong? Explanation is appreciable.

推荐答案

我一般程序的输入循环是这样的:

I usually program input loops like this:

int c;

while ((c = fgetc(fp)) != EOF) {
    /* do something with c here */
}

/* check if EOF came from an end-of-file or an error */
if (ferror(fp)) {
    /* error handling here */
}

您应该一般不会使用这样的循环条件:

You should generally not use a loop condition like this:

while (!feof(fp)) {
    /* do stuff */
}

for (;;) {
    c = fgetc(fp);
    if (feof(fp))
        break;
}

由于遇到IO错误时,这打破。在这种情况下,龟etc 收益 EOF ,但结束文件中的标志未设置。作为一个错误条件通常一直持续到外采取行动的code可能进入一个无限循环。

Because this breaks when an IO error is encountered. In this case, fgetc returns EOF but the end-of-file flag is not set. Your code could enter an infinite loop as an error condition usually persists until external action is taken.

正确的方法是检查的结果龟etc():如果它是等于 EOF ,你可以通常停止阅读进一步的数据无论是在IO错误和档案结尾的状态时,它通常是无法读取更多数据。然后,您应该检查是否发生了错误,并采取适当的行动。

The proper way is to check the result of fgetc(): If it's equal to EOF, you can usually stop reading further data as both in case of an IO error and an end-of-file condition, it's usually not possible to read further data. You should then check if an error occurred and take appropriate action.

这篇关于有什么更好的办法来检查EOF和龟etc的误差()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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