为什么getchar函数()承认EOF只在一行的开始? [英] Why does getchar() recognize EOF only in the beginning of a line?

查看:207
本文介绍了为什么getchar函数()承认EOF只在一行的开始?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个例子是从K&放大器; R书

This example is from the K&R book

#include<stdio.h>


main()
{
    long nc;

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

你能解释我为什么它工作的方式。谢谢你。

Could you explain me why it works that way. Thanks.

^ Z ^ Z无法正常工作或(除非它是在一行的开头)

^Z^Z doesn't work either (unless it's in the beginning of a line)

推荐答案

传统UNIX的tty间pretation EOF 字符是使阻塞阅读无论是煮熟的TTY行缓冲区内的缓冲后读的回报。在新线的起点,它意味着返回0(读数为零字节),并且顺便提一句,0尺寸是怎么检测的文件条件对普通文件的结尾。

Traditional UNIX interpretation of tty EOF character is to make blocking read return after reading whatever is buffered inside a cooked tty line buffer. In the start of a new line, it means read returning 0 (reading zero bytes), and incidentally, 0-sized read is how the end of file condition on ordinary files is detected.

这就是为什么的第一个 EOF 在一行的中间只是强制行的开头是阅读,不做C运行时库检测文件的结束。的两个 EOF 成一排字符产生0大小的读,因为第二个强制空缓冲区为提出的申请。

That's why the first EOF in the middle of a line just forces the beginning of the line to be read, not making C runtime library detect an end of file. Two EOF characters in a row produce 0-sized read, because the second one forces an empty buffer to be read by an application.

$ cat
foo[press ^D]foo <=== after ^D, input printed back before EOL, despite cooked mode. No EOF detected
foo[press ^D]foo[press ^D] <=== after first ^D, input printed back, and on second ^D, cat detects EOF

$ cat
Some first line<CR> <=== input
Some first line <=== the line is read and printed
[press ^D] <=== at line start, ^D forces 0-sized read to happen, cat detects EOF

我假设你的C运行时库模仿上面(有没有特殊的处理描述语义 ^ Z 在水平 KERNEL32 电话,更不用说系统调用,在Windows上)。这就是为什么它可能会检测后EOF ^ Z ^ Z 即使在输入线的中间。

I assume that your C runtime library imitates the semantics described above (there is no special handling of ^Z at the level of kernel32 calls, let alone system calls, on Windows). That's why it would probably detect EOF after ^Z^Z even in the middle of an input line.

这篇关于为什么getchar函数()承认EOF只在一行的开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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