No need for realpath() to call malloc() in du(1)

Print links correctly as well.
This commit is contained in:
sin 2013-10-17 14:06:17 +01:00
parent ac130cbbe0
commit 9e321b69d2

17
du.c
View File

@ -12,6 +12,7 @@
#include "util.h" #include "util.h"
static long blksize = 512; static long blksize = 512;
static char file[PATH_MAX];
static bool aflag = false; static bool aflag = false;
static bool sflag = false; static bool sflag = false;
@ -59,12 +60,12 @@ main(int argc, char *argv[])
if (argc < 1) { if (argc < 1) {
n = du("."); n = du(".");
if (sflag) if (sflag)
print(n, realpath(".", NULL)); print(n, realpath(".", file));
} else { } else {
for (; argc > 0; argc--, argv++) { for (; argc > 0; argc--, argv++) {
n = du(argv[0]); n = du(argv[0]);
if (sflag) if (sflag)
print(n, realpath(argv[0], NULL)); print(n, realpath(argv[0], file));
} }
} }
return EXIT_SUCCESS; return EXIT_SUCCESS;
@ -74,7 +75,6 @@ static void
print(long n, char *path) print(long n, char *path)
{ {
printf("%lu\t%s\n", n, path); printf("%lu\t%s\n", n, path);
free(path);
} }
static char * static char *
@ -127,8 +127,13 @@ du(const char *path)
} else { } else {
m = 512 * st.st_blocks / blksize; m = 512 * st.st_blocks / blksize;
n += m; n += m;
if (aflag && !sflag) if (aflag && !sflag) {
print(m, realpath(dent->d_name, NULL)); if (S_ISLNK(st.st_mode))
snprintf(file, sizeof(file), "%s/%s", cwd, dent->d_name);
else
realpath(dent->d_name, file);
print(m, file);
}
} }
} }
pop(cwd); pop(cwd);
@ -137,6 +142,6 @@ du(const char *path)
} }
if (!sflag) if (!sflag)
print(n, realpath(path, NULL)); print(n, realpath(path, file));
return n; return n;
} }