The statement printf("one")
does not immediately print "one" to the terminal, but it writes the string to the standard output stream (stdout
) - which is usually buffered. Only when this stream is flushed, do its contents get printed to the terminal. Usually, this happens whenever a newline is printed or when the program exits, among other conditions.
The output stream can be forced to flush by calling fflush(stdout)
, which produces the desired result:
#include <stdio.h>
#include <unistd.h>
int main(void) {
printf("one");
fflush(stdout); // Line added
sleep(1);
printf("\r");
printf("two");
return 0;
}
See fflush
for more information. The buffering mode of a stream can be set using the setvbuf
function.
Also, note that the usual main
signature, when using no parameters, is int main(void)
.
Acknowledgements: Thanks to Andreas Wenzel for a correction and the setvbuf
addition.