Search code examples
cconsoleprintf

"\r" in C stops output before it


I wrote a piece of code like this:

#include <stdio.h>
#include <unistd.h>

int main() {
    printf("one");
    sleep(1);
    printf("\r");
    printf("two");
    return 0;
}

It was supposed to first print "one", and then override it by "two" after one second's pause.

But what really happened is that it only print "two" after one second's empty, without printing "one" first. I am confused, can someone figure it out? Thanks a lot.


Solution

  • 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.