diff --git a/Makefile b/Makefile index 453607c..71892f7 100644 --- a/Makefile +++ b/Makefile @@ -25,6 +25,7 @@ LIBUTILSRC = \ libutil/estrtol.c \ libutil/estrtoul.c \ libutil/explicit_bzero.c \ + libutil/human.c \ libutil/passwd.c \ libutil/proc.c \ libutil/putword.c \ diff --git a/df.c b/df.c index 4d595d6..0f0dfea 100644 --- a/df.c +++ b/df.c @@ -13,45 +13,6 @@ static int aflag = 0; static int hflag = 0; static int kflag = 0; -#define CALC_POWER(n, power, base, i) do { \ - while (n > power) { \ - power = power * base; \ - i++; \ - } \ -} while(0) - -static void -print_human( - const char *fsname, - unsigned long long total, - unsigned long long used, - unsigned long long avail, - int capacity, - const char *dir) -{ - long base = 1024; - unsigned long long power_total = base; - unsigned long long power_used = base; - unsigned long long power_avail = base; - char postfixes[] = {'B', 'K', 'M', 'G', 'T', 'P', 'E'}; - int i = 0, j = 0, k = 0; - - total = total * blksize; - used = used * blksize; - avail = avail * blksize; - - CALC_POWER(total, power_total, base, i); - CALC_POWER(used, power_used, base, j); - CALC_POWER(avail, power_avail, base, k); - - total = i ? total / (power_total / base) : total; - used = j ? used / (power_used / base) : used; - avail = k ? avail / (power_avail / base) : avail; - printf("%-12s %9llu%c %9llu%c %9llu%c %7d%% %s\n", - fsname, total, postfixes[i], used, postfixes[j], - avail, postfixes[k], capacity, dir); -} - static int mnt_show(const char *fsname, const char *dir) { @@ -75,7 +36,8 @@ mnt_show(const char *fsname, const char *dir) } if (hflag) - print_human(fsname, total, used, avail, capacity, dir); + printf("%-12s %9s %9s %9s %7d%% %s\n", + fsname, humansize(total*blksize), humansize(used*blksize), humansize(avail*blksize), capacity, dir); else printf("%-12s %9llu %9llu %9llu %7d%% %s\n", fsname, total, used, avail, capacity, dir); diff --git a/libutil/human.c b/libutil/human.c new file mode 100644 index 0000000..7e39ba5 --- /dev/null +++ b/libutil/human.c @@ -0,0 +1,25 @@ +/* See LICENSE file for copyright and license details. */ +#include +#include +#include + +#include "../util.h" + +char * +humansize(off_t n) +{ + static char buf[16]; + const char postfixes[] = "BKMGTPE"; + double size; + int i; + + for (size = n, i = 0; size >= 1024 && i < strlen(postfixes); i++) + size /= 1024; + + if (!i) + snprintf(buf, sizeof(buf), "%ju", (uintmax_t)n); + else + snprintf(buf, sizeof(buf), "%.1f%c", size, postfixes[i]); + + return buf; +}