linux下tree、命令的用法及实现代码

来源:互联网 发布:网络男神排行榜2016 编辑:程序博客网 时间:2024/05/05 20:30

Linux下有这样一个命令,可以把当前目录下的所有文件和子文件以tree的方式显示出来,看下效果

  1. [www.linuxidc.com@localhost test]$ tree  
  2. .  
  3. |-- A  
  4. |-- B  
  5. |-- C  
  6. `-- test2  
  7.     |-- D  
  8.     |-- E  
  9.     `-- F  
  10.   
  11. 3 directories, 4 files  
  12. [crazybaby@localhost test]$   
自己用递归方式用C实现了下,效果如下:
  1. [www.linuxidc.com@localhost test]$ ./a.out   
  2. ./test  
  3.   A  
  4.   a.out  
  5.   B  
  6.   C  
  7.   +test2  
  8.     F  
  9.     +D  
  10.     +E  
  11. [crazybaby@localhost test]$   

这里+号表示directory.

下面是源码:

  1. #include <iostream>  
  2. #include <sys/stat.h>  
  3. #include <dirent.h>  
  4. #include <vector>  
  5. using namespace std;  
  6.   
  7. int showConsoleDir(char* path, int cntFloor) {  
  8.     DIR* dir;  
  9.     DIR* dir_child;  
  10.     struct dirent* dir_ent;  
  11.   
  12.     if ((dir = opendir(path))==NULL) {   //open current directory  
  13.         cout<<"open dir failed!"<<endl;  
  14.         return -1;  
  15.     }  
  16.     while ((dir_ent = readdir(dir))!=NULL) {  
  17.         if ((dir_ent->d_name[0] == '.') || (strcmp(dir_ent->d_name, "..") ==0)){   //if . or .. directory continue  
  18.             continue;  
  19.         }  
  20.         char tName[10000];  
  21.         memset(tName, 0, 10000);  
  22.         snprintf(tName,sizeof(tName),"%s/%s",path,dir_ent->d_name);  
  23.         if ((dir_child = opendir(tName))!=NULL){  //if have a directory  
  24.             int t = cntFloor;  
  25.             while (t--) {  
  26.                 cout<<"  ";  
  27.             }  
  28.             cout<<"+"<<dir_ent->d_name<<endl;  
  29.             showConsoleDir(tName, cntFloor+1);  
  30.         }  
  31.         else  
  32.         {  
  33.             int t = cntFloor;  
  34.             while (t--) {  
  35.                 cout<<"  ";  
  36.             }  
  37.             cout<<dir_ent->d_name<<endl;  
  38.         }     
  39.     }     
  40. }  
  41.   
  42. int main(int argc, char* argv[]){  
  43.     int cntFloor=1;  
  44.     showConsoleDir("./", cntFloor);  
  45.   
  46.       


原创粉丝点击