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

本文介绍了一个使用C语言实现的目录遍历程序。该程序通过递归方式列出指定目录及其子目录下的所有文件和文件夹,并展示了如何利用C标准库函数如opendir(), readdir() 和 lstat() 来获取和解析目录结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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 }

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值