9.自己实现linux中的tree

运行效果:

代码:

  1 #include <stdio.h>
  2 #include <unistd.h>
  3 #include <string.h>
  4 #include <dirent.h>
  5 #include <sys/stat.h>
  6 
  7 void MyTree(char szPath[],int deep)
  8 {
  9     //目录用于遍历
 10     DIR *pDir;
 11     //用于存储文件信息
 12     struct dirent *pDent;
 13     //子目录名字
 14     char szSubPath[PATH_MAX];
 15     
 16     //用于判断文件的类型
 17     struct stat stInfo;
 18     //用来遍历层数,格式输出
 19     int i;
 20     
 21     //打开当前目录,获取目录列表
 22     pDir = opendir(szPath);
 23     //如果打开失败
 24     if(pDir == NULL)
 25     {
 26         perror("Fail to opendir");
 27         return;
 28     }
 29     
 30     //不断循环
 31     while(1)
 32     {
 33         //依次读取文件信息
 34         pDent = readdir(pDir);
 35         //如果读取失败,当前递归结束
 36         if(pDent == NULL)
 37         {
 38             break;
 39         }
 40         
 41         //如果获得了文件信息
 42         
 43         //过滤掉当前目录(.)和上一层目录 (..)
 44         if(strcmp(pDent->d_name,".")==0 || strcmp(pDent->d_name,"..")==0)
 45         {
 46             continue;
 47         }
 48         
 49         //格式输出
 50         for(i=0;i!=deep;i++)
 51         {
 52             printf("");
 53         }
 54         
 55         //如果是目录文件
 56         if(pDent->d_type == DT_DIR)
 57         {
 58             //红色
 59             printf("├── 33[0;31m%s33[0m
",pDent->d_name);
 60             sprintf(szSubPath,"%s/%s",szPath,pDent->d_name);
 61             MyTree(szSubPath,deep+1);
 62         }
 63         else
 64         {
 65             stat(pDent->d_name,&stInfo);
 66             //判断是否是普通文件
 67             if(S_ISREG(stInfo.st_mode))
 68             {
 69                 //判断是否有执行权限
 70                 if(stInfo.st_mode & 0100)
 71                 {
 72                     //青色
 73                     printf("├── 33[1;32m%s33[0m
",pDent->d_name);
 74                 }
 75                 //不能执行的文件
 76                 else
 77                 {
 78                     printf("├── %s
",pDent->d_name);
 79                 }
 80             }
 81             //是否是一个块文件
 82             else if(S_ISFIFO(stInfo.st_mode))
 83             {
 84                     printf("├── 33[1;42m%s33[0m
",pDent->d_name);
 85             }
 86             //其他文件
 87             else
 88             {
 89                 printf("├── %s
",pDent->d_name);
 90             }
 91             
 92         }
 93     }
 94     closedir(pDir);
 95 }
 96 
 97 int main(int argc,char **argv)
 98 {
 99         //char szPath[PATH_MAX];
100         
101         
102         
103         if(argc == 2)
104         {
105             chdir(argv[1]);
106         }
107         
108         //getcwd(szPath,PATH_MAX);
109         //MyTree(szPath,0);
110         MyTree(argv[1],0);
111         
112         return 0;
113 }
原文地址:https://www.cnblogs.com/xiaochi/p/8981988.html