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

 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
",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/
",depth,"",pentry->d_name);
37             printdir(pentry->d_name,depth+4);
38         }
39         else
40             printf("%*s%s
",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: 
",topdir);
55     printdir(topdir,0);
56     printf("Done!
");
57     return 0;
58 }
原文地址:https://www.cnblogs.com/cpsmile/p/4817588.html