预测输出出错! - 使用 "fprintf & stdout" 时这里发生了什么

Predict output gone wrong! - whats happening here while using "fprintf & stdout"

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

上面的程序打印了 "hello-err" 而不是 "hello-out",为什么?

您可以尝试使用

setbuf(stdout, NULL);

停止 stdout 的缓冲,否则你可以这样刷新:

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

来自 C 11 标准 §7.21.5.2 第 2 部分:

If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.

您可以在每个 fprintf () 调用的末尾放置一个 \n,但您可能正在寻找 fflush (stdout)。顾名思义,您可以使用它来刷新输出缓冲区。

像这样...

#include <stdio.h>
#include <unistd.h>

int
main (void)
{
    while (1) {
        fprintf (stdout, "hello-out");
        fflush (stdout);
        fprintf (stderr, "hello-err");

        sleep (1);
    }

    return 0;
}