Progress bar test segfaults
Ok, so this is supposed to display a wget-style progress bar. It segfaults and I don't know where. Any help finding it is appreciated. Thanks!
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
inline int getpercent(int a, int b) {
return (int)((a / b) * 100);
}
/*Dest should be the length of the progress bar*/
/*Returns 0 on error, 1 on success*/
int pbar(const int percent, char *dest) {
int cur, size, tostop, destlen = strlen(dest);
size = destlen - 3;
dest[0] = '|';
dest[destlen - 2] = '|';
dest[destlen - 1] = '\0';
tostop = ((int)((percent / size) * 100));
for (cur = 1; cur <= size; cur++) {
if (cur <= tostop) dest[cur] = '=';
else dest[cur] = ' ';
}
return 1;
}
void progbar(const int amount) {
int current, cols = atoi(getenv("COLUMNS"));
char *bstr = malloc(cols + 1);
for (current = 0; current < cols; current++) bstr[current] = ' ';
bstr[cols] = '\0';
for (current = 0; current < amount; current++) {
printf("\r%s", pbar(getpercent(current, amount), bstr));
usleep(500000);
}
free(bstr);
return;
}
int main(int argc, char **argv) {
int total;
scanf("%d", &total);
progbar(total);
return 0;
}