c - 如果 EOF 是行中的第一个字符,为什么会被识别?

标签 c unix

我写了这个 C 程序:

#include <stdio.h>

main()
{
  int numspaces, numtabs, numnl, c;

  while ((c = getchar()) != EOF){
    if (c == ' ') ++numspaces;
    if (c == '\t') ++numtabs;
    if (c == '\n') ++ numnl;
  }
  printf("Spaces:\t\t%d\nTabs:\t\t%d\nNew lines:\t\t%d\n", numspaces, numtabs, numnl);
}

我认为这个 while 循环必须在我按下 Ctrl+D 和“返回”时结束。如果 Ctrl+D 是我在一行中输入的第一件事,它就会执行。但是,如果我用其他字符(字母、空格、制表符)开始一行,然后 Ctrl+D 然后“返回”- 循环继续。

我在 Mac OS X 终端测试它,我看到它回显 ^D 并且它仍然继续循环。我在这里缺少什么?

最佳答案

CTRL-D 或更准确地说是字符集到 termios 控制结构的 c_cc 字段的 VEOF 条目( stty 是从命令行查询和修改这些设置的最简单方法)被解释为(引用自 Single Unix Specification V4):

Special character on input, which is recognized if the ICANON flag is set. When received, all the bytes waiting to be read are immediately passed to the process without waiting for a , and the EOF is discarded. Thus, if there are no bytes waiting (that is, the EOF occurred at the beginning of a line), a byte count of zero shall be returned from the read(), representing an end-of-file indication. If ICANON is set, the EOF character shall be discarded when processed.

因此,要从终端发送 EOF 指示,您可以在没有字节等待返回时(通常在一行的开头)按一次 CTRL-D,在有一些字节时按两次.

关于c - 如果 EOF 是行中的第一个字符,为什么会被识别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20028909/

相关文章:

linux - shell 导出变量没有生效

c - while 循环外部无法访问 Malloc 内存

python - SWIG:将 2d numpy 数组传递给 C 函数 f(double a[])

c - 了解 qsort() 函数

WNDCLASSEX的概念,良好的编程习惯和系统类的WndProc

c - 我想了解一些关于 C 中指针的知识

linux - Registered I/O 在 Unix/Linux 中的等价物是什么?

linux - 当 src 文件不存在时避免 cat 命令出错

c - 当 SIGINT 信号被忽略时打印字符串

linux - 如何替换某种形式的部分线条?