Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

displaying % completed while executing in C

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!=)

like image 750
Syntax_Error Avatar asked Dec 05 '22 23:12

Syntax_Error


1 Answers

This is essentially two questions rolled in to one:

  • How to calculate percentage based on task flow
  • How to present the calculation

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:

  • Using \r to jump to the beginning of the line
  • Using \b x number of times to move the cursor back

I'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 position

Here'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:

  • Rewrote the last paragraph
  • Replaced my initial bash example with a C example
like image 52
gamen Avatar answered Dec 18 '22 06:12

gamen