Search code examples
cprintfcarriage-return

How to print "\r" to a file


I want to show a progress bar in my program so I add this

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

int main() {
    puts("begin");
    for (int i = 0; i < 100; i++) {
        printf("%d%% finished.\r", i);
        fflush(stdout);
        usleep(100000);
    }
    puts("end");
}

when it outputs to stdout it shows nicely a line indicating the current progress.

However if I direct its output to a file, then all the lines with printf("%d%% finished.\r", i); are missing.

Is it possible to keep all the lines in a file?


Solution

  • It is unlikely that the lines be missing in your output file, but it is possible that copying the file to the terminal occurs so quickly that each line overwrites the previous one without a chance for you to see it. Unlike your program, cat will not pause between the lines. Only the last line will be visible at the end, if it is at least as long as the previous ones.

    Dump the file in hexadecimal with od -x to check the actual file contents.