您的位置:首页 > 运维架构 > Linux

Linux 实现遍历打印子目录中所有文件

2018-02-06 17:20 351 查看
题目要求:实现函数,完成对指定文件的多层级监控,将目录下的所有文件遍历打印出来。

源代码:

1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<fcntl.h>
4 #include<dirent.h>
5 #include<sys/stat.h>
6 #include<sys/types.h>
7 #include<string.h>
8 #include<unistd.h>
9 #include<errno.h>
10
11
12 int scan_dir(char* dir,int depth)              //扫描目录下文件函数
13  {
14     DIR *dp;           //定义目录流指针
15     struct dirent* entry;  //定义dirent 结构体指针
16     struct stat statbuf;   //定义statbuf保存文件属性
17
18     //打开目录
19    dp = opendir(dir);
20    if(dp == NULL)
21    {
22        printf("打开目录失败:%s\n",strerror(errno));
23        return -1;
24    }
25
26    chdir(dir);          //切换到当前目录去获取下一级
27    while((entry = readdir(dp)) != NULL)
28    {
29        lstat(entry->d_name,&statbuf);   //获取下一级成员属性
30        if(S_IFDIR & statbuf.st_mode)    //判断下一级成员是否为目录
31        {
32            if(!strcmp(entry->d_name,".") == 0 || !strcmp(entry->d_name,"..")==0)  //剔除 .和 .. 文件
33            {
34                continue;
35            }
36            printf("%*s%s/\n",depth,"",entry->d_name);   //输出目录名称
37            scan_dir(entry->d_name,depth+4);      //递归调用,扫描下一级目录
38
25
26    chdir(dir);          //切换到当前目录去获取下一级
27    while((entry = readdir(dp)) != NULL)
28    {
29        lstat(entry->d_name,&statbuf);   //获取下一级成员属性
30        if(S_IFDIR & statbuf.st_mode)    //判断下一级成员是否为目录
31        {
32            if(!strcmp(entry->d_name,".") == 0 || !strcmp(entry->d_name,"..")==0)  //剔除 .和 .. 文件
33            {
34                continue;
35            }
36            printf("%*s%s/\n",depth,"",entry->d_name);   //输出目录名称
37            scan_dir(entry->d_name,depth+4);      //递归调用,扫描下一级目录
38
39        }
40        else
41        {
42            printf("%*s%s\n",depth,"",entry->d_name);  //输出属性不是目录的成员
43        }
44    }
45
46     closedir(dp);    //关闭子目录流
47     return 0;
48 }
49
50
51
52 int main()
53 {
54     puts("扫描目录:");
55     scan_dir("./",0);            //可自定义要扫描的路径, ./表示当前目录
56     puts("扫描结束!");
57     return 0;
58 }


&n
4000
bsp; 该函数的作用是遍历目录,将指定路径下的 所有子目录和文件输出到终端上。遍历子目录使用的方法是递归调用,首先,判断子目录流指针所指向的文件是否为目录文件。如果是,该函数将调用自身去遍历子目录;如果不是则输出文件名称,继续遍历当前目录,直到子目录流指向NULL。函数中参数 dir 为路径,指定需要遍历的文件路径,depth参数的作用是在子目录前增加空格的数量,每一轮递归都将增加4个空格,这样个容易显示出目录的层次。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息