找回密码
 用户注册

QQ登录

只需一步,快速开始

查看: 3674|回复: 0

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

[复制链接]
发表于 2011-12-16 11:41:04 | 显示全部楼层 |阅读模式
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  
  •   A  
  •   a.out  
  •   B  
  •   C  
  •   +test2  
  •     F  
  •     +D  
  •     +E  
  • [crazybaby@localhost test]$



这里+号表示directory.
下面是源码:
  1. #include <iostream>
  2.   
  3. #include <sys/stat.h>
  4.   
  5. #include <dirent.h>
  6.   
  7. #include <vector>
  8.   
  9. using namespace std;  
  10.   
  11. int showConsoleDir(char* path, int cntFloor) {  
  12.     DIR* dir;  
  13.     DIR* dir_child;  
  14.     struct dirent* dir_ent;  
  15.   
  16.     if ((dir = opendir(path))==NULL) {   //open current directory
  17.   
  18.         cout<<"open dir failed!"<<endl;  
  19.         return -1;  
  20.     }  
  21.     while ((dir_ent = readdir(dir))!=NULL) {  
  22.         if ((dir_ent->d_name[0] == '.') || (strcmp(dir_ent->d_name, "..") ==0)){   //if . or .. directory continue
  23.   
  24.             continue;  
  25.         }  
  26.         char tName[10000];  
  27.         memset(tName, 0, 10000);  
  28.         snprintf(tName,sizeof(tName),"%s/%s",path,dir_ent->d_name);  
  29.         if ((dir_child = opendir(tName))!=NULL){  //if have a directory   
  30.             int t = cntFloor;  
  31.             while (t--) {  
  32.                 cout<<"  ";  
  33.             }  
  34.             cout<<"+"<<dir_ent->d_name<<endl;  
  35.             showConsoleDir(tName, cntFloor+1);  
  36.         }  
  37.         else  
  38.         {  
  39.             int t = cntFloor;  
  40.             while (t--) {  
  41.                 cout<<"  ";  
  42.             }  
  43.             cout<<dir_ent->d_name<<endl;  
  44.         }     
  45.     }     
  46. }  
  47.   
  48. int main(int argc, char* argv[]){  
  49.     int cntFloor=1;  
  50.     showConsoleDir("./", cntFloor);  
  51.   
  52.       
  53. }  
复制代码
作者:sunstars2009918 发表于2011-12-16 8:05:16 原文链接
您需要登录后才可以回帖 登录 | 用户注册

本版积分规则

Archiver|手机版|小黑屋|ACE Developer ( 京ICP备06055248号 )

GMT+8, 2024-4-29 12:49 , Processed in 0.011761 second(s), 5 queries , Redis On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表