Reputation: 1571
In C, sometimes my output will not get printed to Terminal until I print the newline character \n
. For example:
int main()
{
printf("Hello, World");
printf("\n");
return 0;
}
The Hello World will not get printed until the next printf
(I know this from setting a breakpoint in gdb). Can someone please explain why this happens and how to get around it?
Thanks!
Upvotes: 4
Views: 679
Reputation: 69388
Additionally to fflush()
you can set the buffering options with setvbuf(3).
Upvotes: 4
Reputation: 726987
This is done for performance reasons: passing data to console is too expensive (in terms of execution speed) to do it character-by-character. That is why the output is buffered until the newline is printed: characters are collected in an array until it is time to print, at which time the entire string is passed to the console. You can also force output explicitly, like this:
fflush(stdout);
Upvotes: 8