我有一个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);
}
Run Code Online (Sandbox Code Playgroud)
如果我使用类似命令将数据传输到此程序中
(echo -en '45\n'; echo -en 'text\n') | ./program
scanf()实际上只读取数据.read()只需读取0个字节.
换句话说,程序输出
n: 45 str: read 0 bytes
我怎么能管到的数据都scanf()和read()?
编辑:对不起,我应该澄清:我正在寻找一种方法来做到这一点,而无需修改源代码.感谢那些回答和评论的人.