separate humansize into a util function

also show 1 decimal of human size string like: 4M -> 4.4M
This commit is contained in:
Hiltjo Posthuma 2014-10-18 21:25:00 +00:00 committed by sin
parent ff93350289
commit b6b8fe9591
4 changed files with 24 additions and 19 deletions

View File

@ -17,6 +17,7 @@ LIB = \
util/estrtol.o \ util/estrtol.o \
util/fnck.o \ util/fnck.o \
util/getlines.o \ util/getlines.o \
util/human.o \
util/md5.o \ util/md5.o \
util/mode.o \ util/mode.o \
util/putword.o \ util/putword.o \

20
du.c
View File

@ -85,29 +85,11 @@ main(int argc, char *argv[])
return 0; return 0;
} }
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 static void
print(long n, char *path) print(long n, char *path)
{ {
if (hflag) if (hflag)
print_human(n, path); printf("%s\t%s\n", humansize(n * blksize), path);
else else
printf("%lu\t%s\n", n, path); printf("%lu\t%s\n", n, path);
} }

1
util.h
View File

@ -20,6 +20,7 @@ void enprintf(int, const char *, ...);
double estrtod(const char *); double estrtod(const char *);
long estrtol(const char *, int); long estrtol(const char *, int);
void fnck(const char *, const char *, int (*)(const char *, const char *)); void fnck(const char *, const char *, int (*)(const char *, const char *));
char *humansize(double);
void putword(const char *); void putword(const char *);
void recurse(const char *, void (*)(const char *)); void recurse(const char *, void (*)(const char *));
#undef strlcat #undef strlcat

21
util/human.c Normal file
View File

@ -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;
}