【发布时间】:2022-11-21 01:42:05
【问题描述】:
我想在 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->getchar并且类似的函数永远不会为stdin返回EOF - 在
stdin上使用stat类型的函数 ->stat-ingstdin总是返回 0 的大小 (st_size)。
【问题讨论】:
-
检查 c 是否为 EOF ->
getchar并且类似的函数永远不会为stdin返回EOF那是因为getchar()返回int,而不是char。将返回值塞入char会移除检测EOF的能力。您需要将char c;更改为int c;。 -
@AndrewHenle 将
char c;更改为int c;并将while (1) {更改为while ((c = getchar()) != EOF) {并没有解决我的问题。 -
@AndrewHenle 澄清一下,我现在可以执行
echo "hello world" | ./myprogram,然后打印“hello world”,然后打印“Everything has been read from stdin”,但是以这种方式从stdin读取而不是在sleep期间的用户输入是不是我的目标。 -
@user3121023 我知道终端通常是缓冲的。我的问题是,如果我取消缓冲或按回车键,我怎么知道没有更多内容可读?
-
@user3121023 我更喜欢
termios方法。您介意在答案中提供示例吗?