I have a C program that is taking like 5 minutes to execute. So I was thinking if I can like show the percentage completed or any type of interaction for the user while executing, since a blinking cursor is a bit dull. I was thinking of displaying percentage but can I like erase somehow, eg if task 1 ended I put 25% then after task 2 ends the 25% becomes 50%?
Give me your input on some good interactions cheers!=)
This is essentially two questions rolled in to one:
The first depends on how your program is constructed, and is probably easiest answered by thinking about the problem within the context of your program flow. The second can be done in a myriad of ways, of which the simplest have been explained by others already, namely:
\r
to jump to the beginning of the line\b
x number of times to move the cursor backI've used a third way which hasn't yet been mentioned, and that is to save and restore the cursor position. This allows you to arbitrarily move the cursor around.
\e[s
stores the current cursor position\e[u
restores the cursor to that positionHere's an example:
#include <stdio.h>
#include <unistd.h>
int main(int argc, const char *argv[]) {
int i;
int tasks = 25;
printf("Progress:\e[s");
for(i = 0; i < tasks; i++) {
int pct = ((float) i / tasks) * 100;
printf(" %2d (%3d%%)\e[u", i, pct);
fflush(stdout);
sleep(1);
}
return(0);
}
Note that we don't care where the beginning of the line is: we only reprint the actual percentage. You'll notice that the cursor position is now visible right before the percentage, but you can arbitrarily move it anywhere you like.
This solution assumes that your terminal is capable of understanding these ANSI commands, which can differ from terminal to terminal. Although I think the aforementioned approach is relatively "safe", have a look at terminfo / ncurses for more on that.
Changelog:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With