diff options
author | davidovski <david@davidovski.xyz> | 2022-02-16 23:22:36 +0000 |
---|---|---|
committer | davidovski <david@davidovski.xyz> | 2022-02-16 23:22:36 +0000 |
commit | 89539c200bf93d53ee9b91b521c09bd4607e01d0 (patch) | |
tree | 106981fdbe61c423fafe2d12a74e1b6610601c6a /src/hbar.c | |
parent | e197b62585b15fbe89261922d288bbb901cd0e33 (diff) |
added human formatting for hbar
Diffstat (limited to 'src/hbar.c')
-rw-r--r-- | src/hbar.c | 37 |
1 files changed, 33 insertions, 4 deletions
@@ -20,6 +20,21 @@ #define SAVE_POS "\033[s" #define LOAD_POS "\033[u" +static void human_format(int bytes, char *output) { + char *suffix[] = {"B", "KB", "MB", "GB", "TB"}; + char length = sizeof(suffix) / sizeof(suffix[0]); + + int i = 0; + double dblBytes = bytes; + + if (bytes > 1024) { + for (i = 0; (bytes / 1024) > 0 && i<length-1; i++, bytes /= 1024) + dblBytes = bytes / 1024.0; + } + + sprintf(output, "%.0lf%s", dblBytes, suffix[i]); +} + int main (int argc, char **argv) { struct winsize w; ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); @@ -31,6 +46,7 @@ int main (int argc, char **argv) { int completed = 0; int line = 0; bool terminate = false; + bool human = false; char *color = DEFAULT_COLOR; char *reset = DEFAULT_RESET; @@ -38,14 +54,15 @@ int main (int argc, char **argv) { int opt; int option_index = 0; - const char *optstring = "T:u:c:r:l:t"; + const char *optstring = "T:u:c:r:l:th"; static const struct option opts[] = { {"text", required_argument, 0, 'T'}, {"unit", optional_argument, 0, 'u'}, {"color", optional_argument, 0, 'c'}, {"reset", optional_argument, 0, 'r'}, - {"line", optional_argument, 0, ';'}, - {"terminate", no_argument, 0, 't'} + {"line", optional_argument, 0, 'l'}, + {"terminate", no_argument, 0, 't'}, + {"human-readable", no_argument, 0, 'h'} }; while ((opt = getopt_long(argc, argv, optstring, opts, &option_index)) != -1) { @@ -65,6 +82,9 @@ int main (int argc, char **argv) { case 't': terminate = true; break; + case 'h': + human = true; + break; case 'l': line = atoi(optarg); break; @@ -85,7 +105,16 @@ int main (int argc, char **argv) { } char *count = malloc(width); - sprintf(count, "[%d%s/%d%s]", completed, unit, total, unit); + if (human) { + // i suck at these + char *c = malloc(width); + char *t = malloc(width); + human_format(completed, c); + human_format(total, t); + sprintf(count, "[%s%s/%s%s]", c, unit, t, unit); + } else { + sprintf(count, "[%d%s/%d%s]", completed, unit, total, unit); + } printf(RESET "\r"); printf(color); |