Search code examples
cstdoutstderr

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

The above program prints "hello-err" but not "hello-out", why?


Solution

  • You can try to use

    setbuf(stdout, NULL);
    

    to stop buffering of the stdout or else you can flush like this:

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

    From the C 11 standards §7.21.5.2 part 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.