c - 如何将数据通过管道传输到在 Linux 中调用 scanf() 和 read() 的程序

标签 c linux unix pipe

我有一个如下所示的 C 程序:

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

int main()
{
    int n;
    char str[16];
    scanf("%d", &n);
    printf("n: %d\n", n);

    int count = read(STDIN_FILENO, str, 16);
    printf("str: %s\n", str);
    printf("read %d bytes\n", count);
}

如果我使用像这样的命令将数据通过管道传输到这个程序中

(echo -en '45\n'; echo -en 'text\n') | ./program

只有scanf() 真正读取数据。 read() 简单地读取 0 个字节。

换句话说,程序输出

n: 45
str:
read 0 bytes

如何将数据通过管道传输到 scanf()read()

编辑:抱歉,我应该澄清一下:我正在寻找一种无需修改源代码即可执行此操作的方法。感谢仍然回答和评论的人。

最佳答案

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

int main()
{
    int n;
    char str[16];
    setbuf(stdin, NULL); // Ensure that there's no buffering for stdin
    scanf("%d", &n);
    printf("n: %d\n", n);

    int count = read(STDIN_FILENO, str, 16);
    printf("str: %s\n", str);
    printf("read %d bytes\n", count);
}

正如前面的回答所说,scanf 导致了您的问题,因为它使用了缓冲区。所以您可以通过调用setbuf(stdin,NULL) 来确保它不会。

关于c - 如何将数据通过管道传输到在 Linux 中调用 scanf() 和 read() 的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26697627/

相关文章:

c - 为什么我得到 "Use of undeclared identifier ' malloc'”?

c - 分配内存并在c中保存字符串

c - LuaJIT FFI 有多难?

c++ - 如何在 Debian 7 上安装 FFmpeg 开发者库

unix - Java/Websphere NoSuchProviderException : IBMCertPath 问题

java - Selenium 远程独立服务器 - 驱动程序未知

c++ - 在 C/C++ 程序中使用 Mono SGen 垃圾收集器

java - 无法在 Linux Java 上识别 CRLF

linux - UDP接收程序优先级?

bash - 从标准输入 Bash 逐行读取