主要思路:每一层都先有符号标记再递归
#include <iostream>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string>
using namespace std;
/***************************
* 函数功能: 遍历文件夹
* return: void
* @para folderPath: 文件夹路径
***************************/
void showDirStructure(char* folderPath)
{
/********** BEGIN **********/
//D:/lfy/practiseCode/arithmetic/root
string temp;
temp=folderPath;
string rootname;
int len=temp.length(); // 含#未加工路径长度
int blockcount=0; // 空格数量
int p=0;
// cout<<temp<<endl;
while(temp.find("#",p)!=string::npos){
p=temp.find("#",p);
p=p+1;
blockcount++;
}
// cout<<p<<endl;
// cout<<blockcount<<endl;
for(int i=0;i<blockcount*2;i++){
cout<<" ";
}
for(int i=0;i<len/2;i++){
char c;
c=temp[i];
temp[i]=temp[len-i-1];
temp[len-i-1]=c;
}
if(temp.find("/")){
size_t pos = temp.find("/");
if(blockcount>0){
rootname = temp.substr(blockcount,pos-blockcount);
}else{
rootname = temp.substr(blockcount,pos);
}
int len2=rootname.length();
for(int j=0;j<len2/2;j++){
char d;
d=rootname[j];
rootname[j]=rootname[len2-j-1];
rootname[len2-j-1]=d;
}
}
cout<<"+--"<<rootname<<endl;
DIR *dir;
struct dirent * ptr;
struct stat buf;
stat(folderPath,&buf);
string path = folderPath;
if(blockcount>0){
path.replace(path.begin()+p-blockcount,path.end(),"");
}
// cout<<path<<endl;
char newdirname[2000];
dir = opendir(const_cast<char*>(path.c_str()));
while((ptr=readdir(dir))!=NULL){
if(strcmp(ptr->d_name,".")==0||strcmp(ptr->d_name,"..")==0){
continue;
}
// cout<<"the name: "<<ptr->d_name<<"the type: "<<ptr->d_type<<endl;
if(ptr->d_type==16){
strcpy(newdirname,const_cast<char*>(path.c_str()));
strcat(newdirname,"/");
strcat(newdirname,ptr->d_name);
strcat(newdirname,"#");
while(--blockcount>=0){
strcat(newdirname,"#");
}
// cout<<newdirname<<endl;
showDirStructure(newdirname);
}else{
for(int i =0;i<blockcount*2;i++){
cout<<" ";
}
cout<<" ";
cout<<"--"<<ptr->d_name<<endl;
}
}
closedir(dir);
/********** END **********/
}
int main(int argc, char** argv) {
char *dirname;
string s;
s=dirname;
dirname="D:/lfy/practiseCode/arithmetic/root";
showDirStructure(dirname);
return 0;
}