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
52
53
54
55
56
57
58
59
60
61
62
63
| #include "./dirent.h"
#define MAX_PATH 1024
Dirent *mreaddir02(DIR *dp)
{
struct direct *dirbuf;
static Dirent d; // 静态变量
if ((dirbuf = readdir(dp)) == NULL || dirbuf->d_ino == 0)
return NULL;
d.ino = dirbuf->d_ino;
strncpy(d.name, dirbuf->d_name, DIRSIZ);
d.name[DIRSIZ] = '\0';
return &d;
}
/* dirwalk: apply fcn to all files in dir */
void dirwalk(char *dir, void (*fcn)(char *))
{
char name[MAX_PATH];
Dirent *dp = malloc(sizeof(Dirent));
memset(dp->name, 0, sizeof(dp->name));
DIR *dfd;
// 直接使用系统的opendir()
if ((dfd = opendir(dir)) == NULL)
{
fprintf(stderr, "dirwalk: can't open %s\n", dir);
return;
}
while ((dp = mreaddir02(dfd)) != NULL)
{
if (strcmp(dp->name, ".") == 0 || strcmp(dp->name, "..") == 0)
continue; /* skip self and parent */
if (strlen(dir) + strlen(dp->name) + 2 > sizeof(name))
fprintf(stderr, "dirwalk: name %s %s too long\n",
dir, dp->name);
else
{
sprintf(name, "%s/%s", dir, dp->name);
(*fcn)(name);
}
}
// 直接使用系统提供的closedir()
closedir(dfd);
}
void fsize(char *name)
{
struct stat stbuf;
if (stat(name, &stbuf) == -1)
{
fprintf(stderr, "fsize: can't access %s\n", name);
return;
}
if (S_ISDIR(stbuf.st_mode)) /* directory */
dirwalk(name, fsize);
char timebuf[32];
strftime(timebuf, sizeof(timebuf), "%b %d %R", localtime(&stbuf.st_mtime));
// 展示文件大小,文件的inode号,文件的最后修改时间,文件名
printf("%8ldB %8ld %s %s\n", stbuf.st_size, stbuf.st_ino, timebuf, name);
}
|