You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询printf("")与fprintf(stdin,"")的行为差异原因

为什么printf和fprintf(stdin)的输出行为差异这么大?

核心原因是你误用了fprintf的目标流,stdin是输入流而非输出流,两种写法的具体逻辑拆解如下:

1. printf("hello\n")的正常输出逻辑

printf本质是fprintf(stdout, ...)的语法糖,而stdout(标准输出流)在连接终端时默认是行缓冲模式:

  • 当输出内容包含换行符\n时,行缓冲会被立即刷新,所以"hello"会立刻显示在终端上。
  • 之后程序进入sleep(1)等待1秒,执行fprintf(stderr, "world\n")——stderr(标准错误流)是无缓冲的,所以"world"会直接输出,不需要等待缓冲触发刷新。

2. fprintf(stdin, "hello\n")的无效输出逻辑

stdin是标准输入流,它的设计目的是读取外部输入,不是用来写入输出的:

  • 往stdin写入的数据不会被输出到终端,而是会进入输入流的内部缓冲区,只有后续调用scanf、getchar这类输入函数时才会被读取。
  • 你的测试代码里没有任何读取stdin的逻辑,所以"hello\n"这段数据完全被丢弃了,终端上自然看不到任何输出。
  • 程序执行到sleep(1)后,依旧是fprintf(stderr, "world\n")输出内容,所以看起来只有1秒后显示"world"。

测试代码

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

内容的提问来源于stack exchange,提问作者kang kang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 17:06:09