我发现了一件奇怪的事情。如果我使用
printf("hello\n")
,它将显示“hello”,1秒后显示“world”。但如果我使用fprintf(stdin,"hello\n")
,它只会在1秒后显示“世界”。
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("hello\n"); // fprintf(stdin,"hello\n");
sleep(1);
fprintf(stderr,"world\n");
sleep(1);
return 0;
}
我想知道为什么两个函数的行为不同?
stdin
文件句柄是标准 input 句柄,而不是标准输出句柄。
ISO C 标准明确指出标准输入是“用于读取常规输入”,但没有提及对其进行写入的能力。
换句话说,你的两个片段
printf(x)
和fprintf(stdin, x)
(对于任意x
)是不是同一件事。 fprintf
等效项为 fprintf(stdout, x)
。