ls命令具有一个r选项,可以递归的列出子目录中的内容。请编写一个具有同样功能的程序。

 1 #include <unistd.h>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <dirent.h>
 5 #include <string.h>
 6 #include <sys/stat.h>
 7 /**
 8  * 将数据的目录和深度一起传进来
 9  */
10 void printfdir(char *dir, int depth) {
11 
12     DIR * dp; //对目录进行操作
13     struct dirent *entry; //对目录的数据项进行操作
14     struct stat statbuf;  //用来记录状态信息
15     if ((dp = opendir(dir)) != NULL) {
16         fprintf(stderr, "不能打开目录:%s\n", dir);
17     }
18     chdir(dir); //将当前的工作目重定向
19     while ((entry = readdir(dp)) != NULL) { //使用while来对整个目录进行遍历
20         lstat(entry->d_name, &statbuf);
21         if (S_ISDIR(statbuf.st_mode)) {     //判断是否是目录,如果是目录的话,就递归调用进入下一层
22             if (strcmp(".", entry->d_name) == 0
23                     || strcmp("..", entry->d_name) == 0) {
24                 continue;
25             }
26             printf("%*s%s/\n", depth, " ", entry->d_name);
27             printfdir(entry->d_name, depth + 4);
28         } else {
29             printf("%*s%s/\n", depth, " ", entry->d_name);
30         }
31 
32     }
33     chdir(".."); //如果已经浏览完,将程序当前的工作目录定为父目录
34     closedir(dp);//关闭目录流
35 }
36 
37 int main(void) {
38     printfdir("/home/fjnucse/test",0);
39     return EXIT_SUCCESS;
40 }


作者:kissazi2
出处:http://www.cnblogs.com/kissazi2/
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

原文地址:https://www.cnblogs.com/kissazi2/p/2868273.html