[hackers] [sbase] separate humansize into a util function || Hiltjo Posthuma

From: <git_AT_suckless.org>
Date: Sun, 19 Oct 2014 00:56:58 +0200

commit b6b8fe9591b4e16e0c262965cc48ea6fe1f9ebfc
Author: Hiltjo Posthuma <hiltjo_AT_codemadness.org>
Date: Sat Oct 18 21:25:00 2014 +0000

    separate humansize into a util function
    
    also show 1 decimal of human size string like: 4M -> 4.4M

diff --git a/Makefile b/Makefile
index 70f206c..31b111d 100644
--- a/Makefile
+++ b/Makefile
_AT_@ -17,6 +17,7 @@ LIB = \
         util/estrtol.o \
         util/fnck.o \
         util/getlines.o \
+ util/human.o \
         util/md5.o \
         util/mode.o \
         util/putword.o \
diff --git a/du.c b/du.c
index 98c81cd..ec1a911 100644
--- a/du.c
+++ b/du.c
_AT_@ -86,28 +86,10 @@ main(int argc, char *argv[])
 }
 
 static void
-print_human(long n, char *path)
-{
- long base = 1024;
- long power = base;
- char postfixes[] = {'B', 'K', 'M', 'G', 'T', 'P', 'E'};
- int i = 0;
-
- n = n * blksize;
- while (n > power) {
- power = power*base;
- i++;
- }
-
- n = i ? n / (power / base) : n;
- printf("%lu%c\t%s\n", n, postfixes[i], path);
-}
-
-static void
 print(long n, char *path)
 {
         if (hflag)
- print_human(n, path);
+ printf("%s\t%s\n", humansize(n * blksize), path);
         else
                 printf("%lu\t%s\n", n, path);
 }
diff --git a/util.h b/util.h
index 516a5c2..83ca8e4 100644
--- a/util.h
+++ b/util.h
_AT_@ -20,6 +20,7 @@ void enprintf(int, const char *, ...);
 double estrtod(const char *);
 long estrtol(const char *, int);
 void fnck(const char *, const char *, int (*)(const char *, const char *));
+char *humansize(double);
 void putword(const char *);
 void recurse(const char *, void (*)(const char *));
 #undef strlcat
diff --git a/util/human.c b/util/human.c
new file mode 100644
index 0000000..e0800bf
--- /dev/null
+++ b/util/human.c
_AT_@ -0,0 +1,21 @@
+#include <stdio.h>
+#include <string.h>
+
+#include "../util.h"
+
+char *
+humansize(double n)
+{
+ static char buf[16];
+ const char postfixes[] = " KMGTPE";
+ size_t i;
+
+ for(i = 0; n >= 1024 && i < strlen(postfixes); i++)
+ n /= 1024;
+
+ if(!i)
+ snprintf(buf, sizeof(buf), "%lu%c", (unsigned long)n, postfixes[i]);
+ else
+ snprintf(buf, sizeof(buf), "%.1f%c", n, postfixes[i]);
+ return buf;
+}
Received on Sun Oct 19 2014 - 00:56:58 CEST

This archive was generated by hypermail 2.3.0 : Sun Oct 19 2014 - 01:00:11 CEST