文件结束(EOF)用C [英] End of File (EOF) in C

查看:126
本文介绍了文件结束(EOF)用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在读由里奇和放书C语言程序设计; Kernighan的。而且我pretty困惑EOF在的getchar()功能的使用。

I am currently reading the book C Programming Language by Ritchie & Kernighan. And I am pretty confused about the usage of EOF in the getchar() function.

首先,我想知道为什么EOF的值为-1,为什么的值的getchar()!= EOF 0。原谅我的问题,但我真的不明白。我真的试过,但我不能。

First, I want to know why the value of EOF is -1 and why the value of getchar()!=EOF is 0. Pardon me for my question but I really don't understand. I really tried but I can't.

然后我试图运行书上的例子,可以使用下面的code计数的字符数,但似乎我永远走不出的循环,即使我preSS输入所以我想知道当我到达EOF?

Then I tried to run the example on the book that can count the number of characters using the code below but it seems that I never get out of the loop even if I press enter so I am wondering when would I reach the EOF?

main(){
   long nc;
   nc = 0;
   while (getchar() != EOF)
       ++nc;
   printf("%ld\n", nc);
}

然后,我在C EOF阅读问题同样的问题。大多数人建议,而不是使用EOF,使用的终结\\ n或空终止符'\\ 0',这使得有很大的意义。

Then, I read the same problem at Problem with EOF in C. Most people advised that instead of using EOF, use the terminator \n or the null terminator '\0' which makes a lot of sense.

这是否意味着书上的例子还有另一个目的是什么?

Does it mean that the example on the book serves another purpose?

推荐答案

EOF指示文件结束。换行(这是当你preSS进入会发生什么)不是结束时的文件的,它是一个的的,所以换行没有按到底 ŧ终止此循环。

EOF indicates "end of file". A newline (which is what happens when you press enter) isn't the end of a file, it's the end of a line, so a newline doesn't terminate this loop.

在code是没有错的[*],它只是没有做你似乎会发生什么。它读取与输入的结束,但似乎希望仅读取到行的结尾。

The code isn't wrong[*], it just doesn't do what you seem to expect. It reads to the end of the input, but you seem to want to read only to the end of a line.

EOF的值是-1,因为它必须是从的getchar 任何返回值是一个实际的字符不同。因此,的getchar 返回任何字符值,为unsigned char,转换成int,因此这将是不可否定的。

The value of EOF is -1 because it has to be different from any return value from getchar that is an actual character. So getchar returns any character value as an unsigned char, converted to int, which will therefore be non-negative.

如果你在终端中输入并要挑起一个最终的文件,用CTRL-D(Unix类系统)或Ctrl-Z(Windows)中。然后所有的输入已经被读取之后,的getchar()将返回 EOF ,因此,的getchar()!= EOF 将是错误的,循环终止。

If you're typing at the terminal and you want to provoke an end-of-file, use CTRL-D (unix-style systems) or CTRL-Z (Windows). Then after all the input has been read, getchar() will return EOF, and hence getchar() != EOF will be false, and the loop will terminate.

[*]嗯,这是未定义的行为,如果输入大于LONG_MAX字符由于整数溢出更多,但我们或许可以原谅,在一个简单的例子。

[*] well, it has undefined behavior if the input is more than LONG_MAX characters due to integer overflow, but we can probably forgive that in a simple example.

这篇关于文件结束(EOF)用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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