【问题标题】:Reading everything currently entered in stdin读取当前输入到 stdin 中的所有内容
【发布时间】: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-ing stdin 总是返回 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 方法。您介意在答案中提供示例吗?

标签: c io stdin


【解决方案1】:

这比我用 termios 管理的效果更好。
链接-lncurses

#include <stdio.h>
#include <ncurses.h>
#include <unistd.h>

int main ( void) {
    int ch = 0;

    initscr ( );
    halfdelay ( 2); // tenths of a second that getch waits for input
    noecho ( );
    move ( 1, 1);
    refresh ( );
    sleep ( 10);
    while ( ERR != ( ch = getch ( ))) { // until stdin is empty
        printw ( "%c", ch);
    }
    printw ( "

press enter
");
    while ( ( ch = getch ( ))) {
        if ( '
' == ch) {
            break;
        }
    }
    endwin ( );
    return 0;
}

【讨论】:

    猜你喜欢
    • 2013-02-26
    • 1970-01-01
    • 2010-11-12
    • 2020-10-25
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 2012-08-27
    • 2017-02-10
    相关资源
    最近更新 更多