关于 getchar() 从空文件通过管道传输时如何与 stdin 交互的困惑。
这是简单的 C 代码 test_program.c
#include <stdio.h>
int main( ) {
int c;
printf( "Enter a value :");
c = getchar( );
printf( "\nYou entered: ");
putchar( c );
printf( "\n");
printf( "Enter a value :");
c = getchar( );
printf( "\nYou entered: ");
putchar( c );
printf( "\n");
return 0;
}
好奇当我将一个空文件 (a) 通过管道传输到标准输入时会发生什么...
$ cat a | ./test_program
Enter a value :
You entered: �
Enter a value :
You entered: �
我想我会期望 test_program 阻塞,直到我实际向它提供数据。为什么它从 stdin 读取文件 a 为空的地方,并且为什么它还打印垃圾?
最佳答案
这段代码很好地解释了这一点。
#include <stdio.h>
int main(void)
{
int c = getchar( );
if(c == EOF)
printf("EOF\n");
}
I guess I would have expected test_program to block till I actually feed it data. Why does it read from stdin where the file a is empty and why does it print garbage as well?
当您(尝试)从空流中读取数据时,您将得到一个 EOF。这就是您知道流是空的的方式。
关于c - 管道和 getchar(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58557385/