为什么该C code越野车? [英] Why is this C code buggy?

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

问题描述

在<一个href=\"http://stackoverflow.com/questions/1586423/why-is-this-ocaml-program-faster-than-my-c-program\">another问题,杰里棺材指出以下几点:

这是(可能)没有真正涉及到你的问题,但而(!的feof(fileptr)){是pretty太大的保证错误。

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 仍是(最初)假时,文件的末尾已经达到。 - 后第一个失败的尝试读取过去的文件的末尾它仅变为真

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

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

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