Add human readable output to du(1)

Thanks Jeffrey Picard!
This commit is contained in:
sin 2014-10-16 10:06:27 +01:00
parent 44319a3972
commit 4608d91c6d
3 changed files with 31 additions and 1 deletions

View File

@ -27,6 +27,7 @@ MIT/X Consortium License
© 2014 Laslo Hunhold <dev@frign.de> © 2014 Laslo Hunhold <dev@frign.de>
© 2014 Daniel Bainton <dpb@driftaway.org> © 2014 Daniel Bainton <dpb@driftaway.org>
© 2014 Tuukka Kataja <stuge@xor.fi> © 2014 Tuukka Kataja <stuge@xor.fi>
© 2014 Jeffrey Picard <jeff@jeffreypicard.com>
Permission is hereby granted, free of charge, to any person obtaining a Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"), copy of this software and associated documentation files (the "Software"),

4
du.1
View File

@ -8,6 +8,7 @@ du \- display disk usage statistics
.B \-s .B \-s
.RB ] .RB ]
.RB [ \-k ] .RB [ \-k ]
.RB [ \-h ]
.RI [ file ...] .RI [ file ...]
.SH DESCRIPTION .SH DESCRIPTION
.B du .B du
@ -27,3 +28,6 @@ Display only the grand total for the specified files.
.BI \-k .BI \-k
By default all sizes are reported in 512-byte block counts. By default all sizes are reported in 512-byte block counts.
The -k option causes the numbers to be reported in kilobyte counts. The -k option causes the numbers to be reported in kilobyte counts.
.TP
.BI \-h
Enable human readable output.

27
du.c
View File

@ -16,6 +16,7 @@ static char file[PATH_MAX];
static bool aflag = false; static bool aflag = false;
static bool sflag = false; static bool sflag = false;
static bool kflag = false; static bool kflag = false;
static bool hflag = false;
static long du(const char *); static long du(const char *);
static void print(long n, char *path); static void print(long n, char *path);
@ -53,6 +54,9 @@ main(int argc, char *argv[])
case 'k': case 'k':
kflag = true; kflag = true;
break; break;
case 'h':
hflag = true;
break;
default: default:
usage(); usage();
} ARGEND; } ARGEND;
@ -81,10 +85,31 @@ 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)
{ {
printf("%lu\t%s\n", n, path); if (hflag)
print_human(n, path);
else
printf("%lu\t%s\n", n, path);
} }
static char * static char *