【问题标题】:Why does the print to stdout not happen when using fprintf?为什么使用 fprintf 时不会打印到标准输出?
【发布时间】:2012-07-03 16:01:37
【问题描述】:

我有这个代码:

#include <stdio.h>
#include <unistd.h>
int main()
{
        while(1)
        {
                fprintf(stdout,"hello-out");
                fprintf(stderr,"hello-err");
                sleep(1);
        }
        return 0;
}

输出为hello-errhello-errhello-errhello-errhello-errhello-err 以 1 秒为间隔。 我想知道为什么 hello-out 永远不会被打印出来。

【问题讨论】:

  • 很好,很明确的问题。 +111111!

标签: c stdout stderr printf


【解决方案1】:

您需要fflush stdout 因为通常stdout 是行缓冲的,并且您不会在程序中发出换行符。

            fprintf(stdout,"hello-out");
            fflush(stdout);

stderr 默认没有完全缓冲,所以你不需要fflush 它。

【讨论】:

    【解决方案2】:

    stdout 默认情况下是行缓冲的,这意味着缓冲区将在每个行尾刷新('\n')。 stderr 是无缓冲的,因此每个字符都会自动发送,无需刷新。

    您可以通过在 stdout 输出的末尾放置 \n 来确认这一点。这样两行都将以 1 秒的间隔打印。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-11
      • 2013-05-01
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多