c - 无法从 C 中的 stdin/STDIN_FILENO 读取输入?

标签 c stdin stdio

我有这个命令行参数 -

cat file_name | ./a.out 

问题不在于从 C 程序内的 cat 命令读取,因为我们可以使用 read()fgets()fgetc() 来执行此操作 但我面临的实际问题是在从 cat 读取数据后,我无法使用 fgets 从用户那里获取输入。

这是我的示例代码

while(fgets(buffer, BUFSIZ, stdin ) != NULL )
    puts( buffer ); // Here I have tried strtok( buffer, "\n" ) too.
memset( buffer, 0, BUFSIZ );`

问题出在这一行之后,它没有要求输入,如下所示不起作用 -

puts("Name: ");
fgets( buffer, BUFSIZ, stdin );

帮我看看这里发生了什么问题?

最佳答案

当你执行 cat file_name | 时./a.out 程序的标准输入绑定(bind)到一个管道,将其链接到 cat 的输出。您的程序将永远不会看到用户输入 - 它所到达的流已被前面提到的管道所取代。

请注意,我怀疑通过一些可怕的 POSIX 特定技巧,您可能能够直接为 tty 设备重新打开它,但这只是糟糕的设计。如果您需要从文件读取并接受交互式用户输入,只需接受文件作为命令行参数并使用 stdin 与用户交互。

编辑

这是一个可以尝试的 Unix 特定的拼凑示例,假设进程仍然有一个控制终端。阅读所有原始标准输入后,我打开 /dev/tty (这是进程的控制终端)并将 stdin 重新链接到它。

免责声明:这仅用于娱乐目的,请勿真实执行此操作

#include <stdio.h>
#include <stdlib.h>

void die(const char *msg) {
    fprintf(stderr, "%s\n", msg);
    fputs(msg, stderr);
    exit(1);
}

int main() {
    /* Read all of stdin and count the bytes read (just to do something with it) */
    int ch;
    unsigned long count = 0;
    while((ch = getchar())!=EOF) {
        count++;
    }
    printf("Read %lu bytes from stdin\n", count);
    /* Open the controlling terminal and re-link it to the relevant C library FILE *
     * Notice that the UNIX fd for stdin is still the old one (it's
     * surprisingly complex to "reset" stdio stdin to a new UNIX fd) */
    if(freopen("/dev/tty", "r", stdin) == NULL) {
        die("Failed freopen");
    }

    /* Do something with this newly gained console */
    puts("How old are you?");
    fflush(stdout);
    int age = -1;
    if(scanf("%d", &age)!=1) {
        die("Bad input");
    }
    printf("You are %d years old\n", age);
    return 0;
}

(之前我有一个解决方案,检查 stderrstdout 是否仍然是控制台,这更像是一个拼凑;谢谢 @rici提醒我POSIX有“控制终端”的概念,可以通过/dev/tty访问)

关于c - 无法从 C 中的 stdin/STDIN_FILENO 读取输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50148050/

相关文章:

c++ - vector 排序和更改数据

dart - 为什么Dart隔离中的流在没有接收端口的情况下无法工作

c - 如何在C中读取/解析输入?常见问题

c++ - 如何拦截 C++ 代码中的 printf()?

c - 函数如何创建结构?

c - 如何在二维整数数组上使用 malloc

c - 将字符串中的 IP 传递给 htonl

c++ - 从格式化的输入操作中获取读取的字符数

bash - 没有传递参数时如何读取标准输入?