为什么C程序打印0D而不是0? (当EOF作为Ctrl + D发送时)
OSX 10.6.8,GCC 4.2 86_64
#include /* count lines in input */ main() { int c, nl; nl = 0; while ((c = getchar()) != EOF) if (c == '\n') ++nl; printf("%d\n", nl); }
跑
./a.out
按ctrl+d
发送EOF
0D
它应该只是0.为什么它附加D? 这是什么意思?
我见过这个 – 它也让我很困惑。
终端回显^D
然后从程序输出0
,覆盖插入符号。
您可以通过将程序中的打印格式更改为"\n%d\n"
来certificate这一点。
当问’为什么?’时,我去探索。 答案是在tty设置中。 对于我的终端, stty -a
的输出是:
speed 9600 baud; 65 rows; 120 columns; lflags: icanon isig iexten echo echoe -echok echoke -echonl echoctl -echoprt -altwerase -noflsh -tostop -flusho pendin -nokerninfo -extproc iflags: -istrip icrnl -inlcr -igncr ixon -ixoff ixany imaxbel iutf8 -ignbrk brkint -inpck -ignpar -parmrk oflags: opost onlcr -oxtabs -onocr -onlret cflags: cread cs8 -parenb -parodd hupcl -clocal -cstopb -crtscts -dsrflow -dtrflow -mdmbuf cchars: discard = ^O; dsusp = ^Y; eof = ^D; eol = ; eol2 = ; erase = ^?; intr = ^C; kill = ^X; lnext = ^V; min = 1; quit = ^\; reprint = ^R; start = ^Q; status = ^T; stop = ^S; susp = ^Z; time = 0; werase = ^W;
注意第二行末尾的echoctl
– 它是’回声控制字符’。
$ stty -echoctl $ cat > /dev/null asdsadasd $ stty echoctl $ cat > /dev/null asasada^D $
您无法看到它,但是对于每个cat
命令,我在asd
字符行的末尾键入了一个Control-D ,在点击返回后键入了第二个。 在第二个例子中,提示删除了第二个回显的^D
因此,如果您不喜欢回显控制字符,请关闭回显:
stty -echoctl
shell也可能妨碍; 我用Control-R进行了实验,我的shell( bash
)决定进入
(reverse-i-search)`': aasadasdadadasdadadadadadsad
我输入了’asd’字符的非原始序列,然后键入了Control-R ,这就是我在shell中的结果。 我打断了 我不确定反向搜索是什么,但我怀疑它是Emacs-ish; 这不是我的预期。
在Mac OSX上运行Xcode得到了这个输出:
第一行
第二行
现在我要在返回后按下控制器D.
3