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

 

 

 

posted @   陈哈哈  阅读(4246)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
点击右上角即可分享
微信分享提示