以树形结构的形式输出指定目录下面的所有文件

 1 /*************************************************************************
 2     > File Name: dir.c
 3     > Author: Roc
 4     > Mail:20112022@cqu.edu.cn
 5     > Created Time: 2015年09月15日 星期二 18时33分27秒
 6  ************************************************************************/
 7 
 8 #include<stdio.h>
 9 #include<unistd.h>
10 #include<dirent.h>
11 #include<string.h>
12 #include<sys/stat.h>
13 #include<stdlib.h>
14 
15 void printdir(char *dir, int depth)
16 {
17     DIR *pdir = opendir(dir);//返回一个目录流
18     if(NULL == pdir)
19     {
20         fprintf(stderr,"cannot open directory:%s\n",dir);
21         return;
22     }
23     chdir(dir);//切换到该目录
24     struct dirent *pentry;
25     struct stat statbuf;
26 
27     while((pentry = readdir(pdir)) != NULL)
28     {
29         stat(pentry->d_name,&statbuf);
30         if(S_ISDIR(statbuf.st_mode))
31         {
32             if(strcmp(".",pentry->d_name) == 0 || strcmp("..",pentry->d_name) == 0)
33             {
34                 continue;
35             }
36             printf("%*s%s/\n",depth,"",pentry->d_name);
37             printdir(pentry->d_name,depth+4);
38         }
39         else
40             printf("%*s%s\n",depth,"",pentry->d_name);
41     }
42     chdir("..");//返回上一级目录
43     closedir(pdir);
44 }
45 
46 int main(int argc, char *argv[])
47 {
48     char *topdir, pwd[2] = ".";
49     if(argc < 2)
50         topdir = pwd;
51     else
52         topdir = argv[1];
53 
54     printf("The directory is %s: \n",topdir);
55     printdir(topdir,0);
56     printf("Done!\n");
57     return 0;
58 }

 

转载于:https://www.cnblogs.com/cpsmile/p/4817588.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值