Search code examples
cstdoutcarriage-return

How to redirect stdout with '\r' printed on the same line?


Check below the code snippet of using the character \r:

#include <stdio.h>
#include <unistd.h>
int main() {
    for(int i=1; i<=100; i++) {
        printf("%d%%\r", i);
        fflush(stdout);
        usleep(1e4);
    }
    printf("\n");
    return 0;
}

The output of this program on the console has only 1 line:

$ ./main
100%

However if the output is redirected to a file ./main > main.log, the file has 100 lines:

1%
2%
3%
...
100%

Question:

How do I keep only the last line of output to the log file?


Solution

  • I am assuming this is part of a larger program where the "percentage" may or may not be 100% (otherwise, you could just print 100% right away). So you could check if the output goes to a terminal using isatty. If not, print the "last percentage" value:

    int main(void)
    {
        int b = isatty(STDOUT_FILENO);
        int i;
        for(i=1; i<=100; i++) {
            if (b) printf("%d%%\r", i);
            fflush(stdout);
            usleep(1e4);
        }
        if (!b) printf("%d%%\r", i-1);
        printf("\n");
        return 0;
    }