我有一个如下所示的 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/