buffering behaviour of stdout in c

时光怂恿深爱的人放手 提交于 2019-12-07 15:24:42

问题


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.


回答1:


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;

}



回答2:


I dont think getchar has anything to do with the buffering you are observing in the first code. If you dont press any character and wait for a while ( ie stay inside getchar() ), you'll most probably see an empty file. This happens irrespective of whether you've stalled the program with getchar, sleep or a while(1).

Now you press Ctrl-C for which your program has no handler registered and hence your program terminates abruptly. Whether buffers/streams are flushed on abrupt program termination is implementation defined. Read the full story here

Why is data not being flushed to file on process exit?

For example, on my system ( Windows 7, Code Blocks which uses gcc and mingw framework internally ), I can see 45 indeed being flushed into the file irrespective of using getchar or anything when I terminate it abruptly. ie on my system, the implementation is flushing data to the file on abrupt program termination.

So, the bottom line is, what happens when you do things in a non-normal fashion is implementation defined!

But the second case is indeed a curious one where getchar seems to be flushing the stdout buffer. I shall update on that as soon as I find the exact cause of why getchar is/seems-to-be flushing stdout buffer




回答3:


The first case you are writing to a physical file. fopen, fclose are buffered I/O depends on the implementation, data may not be committed immediately until the buffer is full. Calling fclose() will cause the buffer to be written to disk.

The second case you are writing to STDIO and data written to STDIO normally show up immediately.



来源:https://stackoverflow.com/questions/11339519/buffering-behaviour-of-stdout-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!