手机版
你好,游客 登录 注册
背景:
阅读新闻

Linux基础教程:实现Linux下tree命令

[日期:2011-08-19] 来源:Linux社区  作者:crazyjixiang [字体:大 中 小]

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.      
  47. } 
linux
相关资讯       Linux tree命令 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款