-
Notifications
You must be signed in to change notification settings - Fork 0
/
8.05-du.c
51 lines (43 loc) · 1.07 KB
/
8.05-du.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#define MAX_PATH 1024
void du(char *fname) {
struct stat finfo;
if (lstat(fname, &finfo) < 0) {
fprintf(stderr, "stat: %s: %s\n", fname, strerror(errno));
return;
}
if (!S_ISDIR(finfo.st_mode)) {
printf("%8lu %s\n", finfo.st_size, fname);
return;
}
DIR *dir = opendir(fname);
if (dir == NULL) {
fprintf(stderr, "opendir: %s: %s\n", fname, strerror(errno));
return;
}
struct dirent *dentry;
while ((dentry = readdir(dir))) {
if (!strcmp(dentry->d_name, ".") || !strcmp(dentry->d_name, "..")) {
continue;
}
char path[MAX_PATH];
snprintf(path, sizeof(path), "%s/%s", fname, dentry->d_name);
du(path);
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc == 1) {
du(".");
return EXIT_SUCCESS;
}
for (int i = 1; i < argc; i++) {
du(argv[i]);
}
return EXIT_SUCCESS;
}