- 论坛徽章:
- 0
|
linux下tree、命令的用法及实现代码 .
Linux下有这样一个命令,可以把当前目录下的所有文件和子文件以tree的方式显示出来,看下效果- 01.[www.linuxidc.com@localhost test]$ tree
- 02..
- 03.|-- A
- 04.|-- B
- 05.|-- C
- 06.`-- test2
- 07. |-- D
- 08. |-- E
- 09. `-- F
- 10.
- 11.3 directories, 4 files
- 12.[crazybaby@localhost test]$
复制代码 自己用递归方式用C实现了下,效果如下:- 01.[www.linuxidc.com@localhost test]$ ./a.out
- 02../test
- 03. A
- 04. a.out
- 05. B
- 06. C
- 07. +test2
- 08. F
- 09. +D
- 10. +E
- 11.[crazybaby@localhost test]$
复制代码 这里+号表示directory.
下面是源码:- 01.#include <iostream>
- 02.#include <sys/stat.h>
- 03.#include <dirent.h>
- 04.#include <vector>
- 05.using namespace std;
- 06.
- 07.int showConsoleDir(char* path, int cntFloor) {
- 08. DIR* dir;
- 09. 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.}
复制代码 |
|