ascii progress bars

Sometimes you want to display a progress routine in C/C++, without resorting to termcap/curses. The simplest mechanism you can use is:

for (i = 0; i < 10000; i++){
    printf("\rIn Progress: %d", i/100);
}
printf("\n");

This yields flickering on the display as the cursor moves back and forth over the entire line reprinting it. This gets worse with larger amounts of display data. If your progress routine is simple like this, then you can use another mechanism – the backspace \b, rather than the reset \r. You take advantage of printf reporting the number of characters it displayed as a return code, and then only display the required number of backspace characters.

So for example:

printf("In Progress: ");
int lastprinted = 0;
for (i = 0; i < 10000; i++){
    while (lastprinted--) printf("\b");
    lastprinted = printf("%d", i/100);
}
printf("\n");

This way you get to only print a few characters every refresh, which minimizes the flicker.