Printf on Linux and Windows
Here is the C code:
int i; printf("This text is printed\nThis text is not until the for loop end."); for (i = 5; i > 0; i--) { printf("%d", i); sleep(1); } Why doesn't the rest of the text after '\n' print before the start of the for loop? Even printf inside the for loop prints only after the end of the loop. If I put '\n' at the end of the text, it prints, but I don't need a new line.
This only happens on Linux and not on Windows (just changed sleep (1) to Sleep (1000) and added windows.h).
This is caused by output buffering. When you call printf, the output is not printed immediately. It is written to the buffer for output in the future. Usually the \n character causes a buffer flush automatically. You can also manually clear the stdout buffer:
printf("This text is printed\nThis text is not until the for loop end."); fflush(stdout); Take a look at setvbuf() and _IONBF vs _IOLBF vs _IOFBF . By default, when the output refers to the terminal, the output is buffered by line ( _IOLBF ). This means that the output appears only when a new line is included. _IONBF not buffered, sometimes reserved for standard error (although this can also be buffered in a string). _IOFBF fully buffered; the output will not be displayed until the internal buffer is full, or you explicitly fflush() output (or, sometimes, if you are reading from standard input). If you write to a pipe or file, the output will usually be completely buffered.
In general, you should expect the output to finish with a new line if you want to see them in a timely manner - despite using the examples on Windows. (This is a common meme on Stack Overflow that reliably identifies when a program is written for Windows.)
The stdout buffer is not specified by the C standard. But POSIX implies (does not require) that usually stdout is string buffered when it is connected to the terminal, otherwise it is fully buffered.
Linux follows this POSIX convention, but Windows does not. You can change the default behavior with setvbuf or use fflush to clear the output guaranteed by the C standard.