免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1372 | 回复: 1
打印 上一主题 下一主题

linux下tree、命令的用法及实现代码 . [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-12-19 17:15 |只看该作者 |倒序浏览
linux下tree、命令的用法及实现代码 .












Linux下有这样一个命令,可以把当前目录下的所有文件和子文件以tree的方式显示出来,看下效果
  1. 01.[www.linuxidc.com@localhost test]$ tree  
  2. 02..  
  3. 03.|-- A  
  4. 04.|-- B  
  5. 05.|-- C  
  6. 06.`-- test2  
  7. 07.    |-- D  
  8. 08.    |-- E  
  9. 09.    `-- F  
  10. 10.  
  11. 11.3 directories, 4 files  
  12. 12.[crazybaby@localhost test]$   
复制代码
自己用递归方式用C实现了下,效果如下:
  1. 01.[www.linuxidc.com@localhost test]$ ./a.out   
  2. 02../test  
  3. 03.  A  
  4. 04.  a.out  
  5. 05.  B  
  6. 06.  C  
  7. 07.  +test2  
  8. 08.    F  
  9. 09.    +D  
  10. 10.    +E  
  11. 11.[crazybaby@localhost test]$   
复制代码
这里+号表示directory.

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

论坛徽章:
0
2 [报告]
发表于 2011-12-19 21:23 |只看该作者
学习喽
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP