我希望在10秒后读取stdin中的所有内容并停止。我目前编写的代码如下:
#include <stdio.h>
#include <stdlib.h>
int main() {
sleep(10);
char c;
while (1) { // My goal is to modify this while statement to break after it has read everything.
c = getchar();
putchar(c);
}
printf("Everything has been read from stdin");
}
当在10秒内输入字母"c"时,程序应该打印出"c"(在sleep
执行之后),然后打印出"Everything has been read from stdin"。
目前我已经尝试过:
- 检查是否输入了
c
的文件结束符EOF -> 对于stdin
,getchar
和类似的函数永远不会返回EOF
- 在
stdin
上使用类似stat
的函数->对stdin
进行stat
操作总是返回0作为大小(st_size
)。
getchar
和类似的函数从stdin
中不会返回EOF
。这是因为getchar()
返回的是int
而不是char
。将返回值强制转换为char
会导致无法检测到EOF
。你需要将char c;
改为int c;
。 - Andrew Henlechar c;
改为int c;
,并将while (1) {
改为while ((c = getchar()) != EOF) {
对我来说并没有解决问题。 - gurkensaasecho "hello world" | ./myprogram
,然后它会打印出 "hello world",接着打印出 "Everything has been read from stdin",但是这种方式读取stdin
而不是在sleep
期间读取用户输入并不是我的目标。 - gurkensaastermios
方法。你能否在回答中提供一个示例? - gurkensaas