1. 程式人生 > >c++刷題 檔案檢視器(有格式遍歷輸出資料夾目錄)

c++刷題 檔案檢視器(有格式遍歷輸出資料夾目錄)

主要思路:每一層都先有符號標記再遞迴

#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;
	}