Reputation: 5417
The following program shows how buffered I/O can cause problems in programs when errors like 'divide by zero' happen:
int main()
{
int a = 1, b = 0, c;
printf("Dividing...");
c = a/b;
printf("Answer is: %d\n", c);
return 0;
}
The output is Floating point exception (core dumped)
.
Fair enough. But surprisingly, if I changed the first printf to printf("Dividing...\n");
, this text actually gets printed before the program crashes (I'm running GCC on Linux, by the way).
Am I to conclude that adding a newline is equivalent to flushing? And if so, if all my printf()
strings end in \n
, I'm actually depriving myself of the benefits of buffered I/O?
Upvotes: 3
Views: 519
Reputation: 12629
If your standard output is going to a terminal, yes, it's equal to flushing, as printf()
will use line-based buffering.
If it's redirected to a file, then no. In this case printf()
uses much bigger buffers, usually corresponding to file system block sizes or whatever, to optimize IO.
Upvotes: 4