linux下tree、命令的用法及实现代码
linux下tree、命令的用法及实现代码Linux下有这样一个命令,可以把当前目录下的所有文件和子文件以tree的方式显示出来,看下效果
[www.linuxidc.com@localhost test]$ tree
.
|-- A
|-- B
|-- C
`-- test2
|-- D
|-- E
`-- F
3 directories, 4 files
$
自己用递归方式用C实现了下,效果如下: [www.linuxidc.com@localhost test]$ ./a.out
./testA
a.out
B
C
+test2
F
+D
+E
$ 这里+号表示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 == '.') || (strcmp(dir_ent->d_name, "..") ==0)){ //if . or .. directory continue
continue;
}
char tName;
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);
} 谢谢分享了
页:
[1]