为什么 printf("") 与 printf(stdin,"") 不同?

问题描述 投票:0回答:1

我发现了一件奇怪的事情。如果我使用

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;
}

我想知道为什么两个函数的行为不同?

c printf
1个回答
0
投票

stdin
是标准 input 句柄,而不是标准输出句柄。

ISO C 标准明确指出标准输入是“用于读取常规输入”,但没有提及对其进行写入的能力。

换句话说,你的两个片段

printf(x)
fprintf(stdin, x)
(对于任意
x
)是不是同一件事。
fprintf
等效项为
fprintf(stdout, x)

© www.soinside.com 2019 - 2024. All rights reserved.