Search code examples
cstdiooutput-buffering

buffering behaviour of stdout in c


When I run the first code and press ctrl-c immediately there will be no 45 written out to the file. But when I run the second code, I do get 45.

I couldn't come to the reason why this behavior happens in the below code? If stdout is line buffered shouldn't output come after I enter a character? What am I missing?

First code:

#include<stdio.h>
#include<stdlib.h>
int main()
{
   FILE *fp=stdout;
   fp=fopen("myfile","w");
   fprintf(fp,"%d",45);
   getchar();
  // return 0;

}

Second code:

#include<stdio.h>
#include<stdlib.h>
int main()
{
   FILE *fp=stdout;
   fprintf(fp,"%d",45);
   getchar();
  // return 0;

}

PS: I'm using GCC and the platform is Linux.


Solution

  • Whats causing confusion is getchar(), seems like when it is called it is flushing stdout.

    If you replace getchar() with something like sleep(10) then you 45 won't be printed.

    #include<stdio.h>
    #include<unistd.h>
    #include<stdlib.h>
    int main()
    {
       FILE *fp=stdout;
       //fp=fopen("myfile","w");
       fprintf(fp,"%d",45);
       sleep(10);
       //getchar();
      // return 0;
    
    }