Why does the print to stdout not happen when using fprintf?

insane picture insane · Jul 3, 2012 · Viewed 7.4k times · Source

I have this code:

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

The output is hello-err hello-err hello-err hello-err hello-err hello-err at 1 sec intervals. I want to know why hello-out never gets printed.

Answer

ouah picture ouah · Jul 3, 2012

You need to fflush stdout because usually stdout is line buffered and you don't issue a new line character in your program.

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

stderr is not fully buffered by default so you don't need to fflush it.