Skip to content

Instantly share code, notes, and snippets.

@jampajeen
Created October 27, 2016 21:10
Show Gist options
  • Save jampajeen/2897e795e7e4b78bb5e677a480ee66f0 to your computer and use it in GitHub Desktop.
Save jampajeen/2897e795e7e4b78bb5e677a480ee66f0 to your computer and use it in GitHub Desktop.
console progress bar
#include <stdio.h>
#include <cstdlib>
#define PROGRESS_BAR_STR "================================="
#define PROGRESS_BAR_WIDTH sizeof(PROGRESS_BAR_STR)
void print_progress_bar(size_t completed, size_t total) {
const char operation[] = "Downloaded";
const char prefix[] = " kMGT";
int lpad = (int) (((double) completed / total) * PROGRESS_BAR_WIDTH);
int rpad = PROGRESS_BAR_WIDTH - lpad;
double percentage = (completed * 100.0) / total;
int c = 0, t = 0;
double dc = completed;
double dt = total;
while (dc >= 1024) {
dc /= 1024;
c++;
}
while (dt >= 1024) {
dt /= 1024;
t++;
}
printf(" \r %3.0f%% %s [%.*s%*s] %5.2f%cB / %.2f%cB ", percentage, operation, lpad, PROGRESS_BAR_STR, rpad, "", dc, prefix[c], dt, prefix[t]);
fflush(stdout);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment