免费注册 查看新帖 |

Chinaunix

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

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

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








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

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

论坛徽章:
0
2 [报告]
发表于 2011-12-19 11:13 |只看该作者
谢谢分享了
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP