My very simple C solution:
#include <stdio.h>
#define S_(x) #x
#define S(x) S_(x)
#define PBWIDTH 64
#define PBCHAR '#'
static void progressbar(unsigned percent) {
char pbstr[PBWIDTH];
memset(pbstr, PBCHAR, PBWIDTH);
fprintf(stderr, "\r[%-" S(PBWIDTH) ".*s] %u%%",
percent * PBWIDTH / 100, pbstr, percent);
}
int main(void) {
progressbar(70);
fprintf(stderr, "\n");
}
Outputs:
[############################################ ] 70%
The memset
should be optimized to 1 or 2 vector instructions when compiled for modern CPUs, much smaller than storing the whole string statically and equally fast.
In the programs I use it in, I like to print 0% this way, before the loop that calls progressbar
:
fprintf(stderr, "[%-" S(PBWIDTH) ".*s] %u%%", 0, "", 0);
If you prefer the number to be before the bar, change the fprintf
in progressbar
:
fprintf(stderr, "\r%3u%% [%-" S(PBWIDTH) ".*s]",
percent, percent * PBWIDTH / 100, pbstr);
And if you do the optional 0% bit:
fprintf(stderr, "%3u%% [%-" S(PBWIDTH) ".*s]", 0, 0, "");
Modify this all as you see fit. :)
wget
process is not an option ? – Flabellum