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.
下面是源码:
- #include <iostream>
- #include <sys/stat.h>
- #include <dirent.h>
- #include <vector>
- using namespace std;
- int showConsoleDir(char* path, int cntFloor) {
- DIR* dir;
- DIR* dir_child;
- struct dirent* dir_ent;
- if ((dir = opendir(path))==NULL) { //open current directory
- cout<<“open dir failed!”<<endl;
- return -1;
- }
- while ((dir_ent = readdir(dir))!=NULL) {
- if ((dir_ent->d_name[0] == ‘.’) || (strcmp(dir_ent->d_name, “..”) ==0)){ //if . or .. directory continue
- continue;
- }
- char tName[10000];
- memset(tName, 0, 10000);
- snprintf(tName,sizeof(tName),“%s/%s”,path,dir_ent->d_name);
- if ((dir_child = opendir(tName))!=NULL){ //if have a directory
- int t = cntFloor;
- while (t–) {
- cout<<” “;
- }
- cout<<“+”<<dir_ent->d_name<<endl;
- showConsoleDir(tName, cntFloor+1);
- }
- else
- {
- int t = cntFloor;
- while (t–) {
- cout<<” “;
- }
- cout<<dir_ent->d_name<<endl;
- }
- }
- }
- int main(int argc, char* argv[]){
- int cntFloor=1;
- showConsoleDir(“./”, cntFloor);
- }