曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 4637|回复: 2
打印 上一主题 下一主题

目录扫描

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34397
跳转到指定楼层
楼主
发表于 2009-2-13 15:49:31 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
功能:打印出目录信息

代码
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 }

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34397
沙发
 楼主| 发表于 2009-2-13 21:03:25 | 只看该作者
在命令行接收需要查看的目录参数
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 }

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34397
板凳
 楼主| 发表于 2009-2-13 17:34:24 | 只看该作者
程序分析:

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 函数,进行递归显示。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-6-18 06:36 , Processed in 0.081593 second(s), 21 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表