These are, in fact, two questions recounted to one:
- How to calculate percentage based on task flow.
- How to submit a calculation
First of all, it depends on how your program is built, and it is probably easiest to answer the thought of a problem in the context of your program flow. The second can be done in a variety of ways, of which the simplest have already been explained by others, namely:
- Using
\r to go to the beginning of a line - Using
\b x the number of times to move the cursor back
I used the third method, which has not yet been mentioned, and this is to save and restore the cursor position. This allows you to arbitrarily move the cursor.
\e[s saves the current cursor position\e[u restores the cursor to this position
Here is 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 line starts: we retype the actual percentage . You will notice that the cursor position is now visible directly in front of the percentage, but you can arbitrarily move it anywhere.
This solution assumes that your terminal is capable of understanding these ANSI commands, which may vary from terminal to terminal. Although I think the above approach is relatively "safe", check out terminfo / ncurses to find out more about this.
Changelog:
- Rewrote the last paragraph
- Replaced my original bash example C example
gamen source share