Why doesn't C print to the shell before a new line?

In C, sometimes my output will not be printed on the terminal until I print a newline character \n . For instance:

 int main() { printf("Hello, World"); printf("\n"); return 0; } 

Hello World will not print until the next printf (I know this from setting a breakpoint in gdb). Can someone explain why this is happening and how to get around it?

Thanks!

+4
source share
2 answers

This is done for performance reasons: transferring data to the console is too expensive (in terms of speed of execution) to do this by character. Therefore, the output is buffered until a new line is printed: the characters are collected in an array until the print time is reached, after which the entire line will be transmitted to the console. You can also force output, for example:

 fflush(stdout); 
+8
source

In addition to fflush() you can set setvbuf (3) buffering options .

+4
source

All Articles