linux 下的文件目录操作之遍历目录

  通过递归调用读取目录和文件信息去遍历整个目录:

  示例代码:

 1 #include <unistd.h>
 2 #include <stdio.h>
 3 #include <dirent.h>
 4 #include <string.h>
 5 #include <sys/stat.h>
 6 #include <stdlib.h>
 7 
 8 
 9 void printdir(char * dir, int depth)
10 {
11     DIR * dp = opendir(dir);
12     if (NULL == dp)
13     {
14         fprintf(stderr, "cannot open directory: %s\n", dir);
15         return;
16     }
17     chdir(dir);
18     struct dirent * entry;
19     struct stat statbuf;
20     while ((entry = readdir(dp)) != NULL)
21     {
22         stat(entry->d_name, &statbuf);
23         if (S_ISDIR(statbuf.st_mode))
24         {
25             if (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0)
26                 continue;
27             printf("%*s%s/\n", depth, "", entry->d_name);
28             printdir(entry->d_name, depth + 4);
29         }
30         else
31             printf("%*s%s\n", depth, "", entry->d_name);
32         //printf("%*s",4,"*"); 该函数表示输出"___*",前面输出3个空格。
33         //如果是printf("%*s",4,"**");则表示输出"__**",前面输出2个空格。
34     }
35     chdir("..");
36     closedir(dp);
37 }
38 
39 int main(int argc, char * argv[])
40 {
41     char * topdir, pwd[2] = ".";
42     if (argc < 2)
43         topdir = pwd;
44     else
45         topdir = argv[1];
46     printf("Directory scan of %s\n", topdir);
47     printdir(topdir, 0);
48     printf("done.\n");
49     exit(0);
50 }

 

  运行结果:

  

 

转载于:https://www.cnblogs.com/general0878/p/7214244.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值