曲径通幽论坛

标题: 目录扫描 [打印本页]

作者: beyes    时间: 2009-2-13 15:49
标题: 目录扫描
功能:打印出目录信息

代码
01 #include <unistd.h>
02 #include <stdio.h>
03 #include <dirent.h>
04 #include <string.h>
05 #include <sys/stat.h>
06 #include <stdlib.h>
07
08
09 void printdir(char *dir, int depth)
10 {
11         DIR *dp;
12         struct dirent *entry;
13         struct stat statbuf;
14
15         if( (dp = opendir(dir)) == NULL ) {
16                 fprintf(stderr, "cannot open directory: %s\n", dir);
17                 return;
18         }
19
20         chdir(dir);
21
22         while((entry = readdir(dp)) != NULL) {
23                 lstat(entry->d_name, &statbuf);
24                 if(S_ISDIR(statbuf.st_mode)) {
25                         /* Found a directory, but ignore . and .. */
26                 if(strcmp(".",entry->d_name) == 0 ||
27                    strcmp("..",entry->d_name) == 0 )
28                 continue;
29
30                 printf("%*s%s/\n",depth, "", entry->d_name);
31
32                 /* Recurse at a new indent level */
33
34                 printdir(entry->d_name,depth+4);
35         }
36
37                 else printf("%*s%s\n",depth,"",entry->d_name);
38         }
39
40         chdir("..");
41         closedir(dp);
42 }
43
44
45
46 int main()
47 {
48         printf("Directory scan of /root/C:\n");
49         printdir("/root/C",0);
50         printf("done.\n");
51
52         exit(0);
53
54 }

作者: beyes    时间: 2009-2-13 17:34
程序分析:

15. 对一个目录操作,首先一般需要用 opendir 测试目录是否可以被访问并打开,如果无法打开函数返回 NULL;如果可以打开,则返回一个目录流 DIR 指针,这个指针也是后续对目录操作的基石。

20. 在确定可以打开目录后,使用 chdir 函数进入这个目录。

22. 根据得到的目录流 DIR,使用 opendir 函数读取目录,然后返回 struct dirent 结构的指针并赋给 entry 。

23. lstat 函数根据文件名(目录文件名和普通文件名 entry->d_name)参数,把得到的文件状态信息传入结构 statbuf 中。

24. 使用宏 S_ISDIR 判断文件是不是目录文件

26-27. 看目录是不是当前目录"."或者是上一级目录"..",是的话不处理。

30. 打印出目录的名称

34. 遇到目录,就使用 printdir 函数,进行递归显示。
作者: beyes    时间: 2009-2-13 21:03
在命令行接收需要查看的目录参数
01 int main(int argc, char *argv[])
02 {
03         char *topdir = ".";
04         if(argc >= 2)
05                 topdir = argv[1];
06
07         printf("Directory scan of %s:\\n",topdir);
08         printdir("tipdir",0);
09         printf("done.\\n");
10
11         exit(0);
12
13 }





欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2