Skip to content

Instantly share code, notes, and snippets.

@edgesider
Last active May 20, 2019 15:37
Show Gist options
  • Save edgesider/90f00c0b91dd2470ee126b3d81b3b89a to your computer and use it in GitHub Desktop.
Save edgesider/90f00c0b91dd2470ee126b3d81b3b89a to your computer and use it in GitHub Desktop.
progress in c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int progress(char *buf, ssize_t bufsize,
int completed, int length,
char cell, char empty,
char begin, char end)
{
int i = 0;
char *p = buf;
char *bufend;
if (bufsize < 2 + length + 1) return -1;
bufend = buf + bufsize - 1;
cell = cell == '\0' ? '-' : cell;
empty = empty == '\0' ? '|' : empty;
completed = completed <= length ? completed : length;
if (begin != '\0' && p < bufend)
*p++ = begin;
for (i = 0; i < completed && p < bufend; i++)
*p++ = cell;
for (; i < length && p < bufend; i++)
*p++ = empty;
if (end != '\0' && p < bufend)
*p++ = end;
*p++ = '\0';
return p - buf;
}
void assest(int i, char *msg)
{
if (!i) {
dprintf(2, "assest error %s\n", msg);
exit(-1);
}
}
int main()
{
char buf[512];
assest(-1 == progress(buf, 1, 20, 100, '*', ' ', '[', ']'), "");
assest(-1 == progress(buf, 50, 20, 100, '*', ' ', '[', ']'), "");
assest(53 == progress(buf, 53, 20, 50, '*', ' ', '[', ']'), "");
assest(51 == progress(buf, 53, 20, 50, '*', ' ', '\0', '\0'), "");
assest(51 == progress(buf, 53, 100, 50, '*', ' ', '\0', '\0'), "");
for (int i = 0; i <= 100; i++) {
int l = progress(buf, sizeof(buf), i, 100, '\0', '\0', '[', ']');
assest(l != -1, "");
dprintf(1, "\r%s", buf);
usleep(1 * 10e4);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment