1. 程式人生 > >檔案檢視器(c++)

檔案檢視器(c++)

第2關:檔案檢視器

挑戰任務

參加“綠盟杯”競賽的小紅遇到一個問題,她想要編寫程式碼實現一個檔案檢視器,要實現指定資料夾下所有檔案以及資料夾目錄結構的展示。

你來幫她實現這個功能吧。

程式設計要求

程式設計實現對給定資料夾目錄結構的展示,如果是資料夾則在其名字之前加上+--若是檔案則加上--,上級目錄與下級目錄、下級檔案用兩個空格作為間隔,同級下依照資料夾、檔案的首字母順序依次列印;補充完善右側程式碼區中的showDirStructure(char *folderPath)函式實現要求的功能,其中函式引數含義如下:

  • folderPath:指定要顯示的資料夾

測試說明

樣例1

輸入:src/step2/root

輸出:

樣例2

輸入:src/step2/dir

輸出:

提示: 在C語言中使用readdir函式可以獲取目錄內容,使用stat函式判斷檔案型別。

你可以通過如下連結下載本關涉及到的目錄檔案:
https://www.educoder.net/attachments/download/200773/step2Dir.zip


開始挑戰吧,祝你成功!

/***************************
 * 函式功能: 遍歷資料夾
 * return: void
 * @para folderPath: 資料夾路徑
***************************/
void showDirStructure(char *folderPath)
{
	/********** BEGIN **********/
	static int floor=0;	//層數
	
	for(int i=0;i<floor*2;i++)
		cout<<" ";	//輸出前置空格
	char buf[256];
	int len=0;
	
	for(int i= strlen(folderPath)-1;folderPath[i]!='/';i--) 
		buf[len++]=folderPath[i];
	buf[len]='\0';
	for(int i=0;i<len/2;i++){
		char t=buf[i];
		buf[i]=buf[len-1-i];
		buf[len-1-i]=t;
	}
	cout<<"+--"<<buf<<endl;
	
	DIR *dir=opendir(folderPath);
	struct dirent *i=NULL;
	
	while((i=readdir(dir))!=NULL){
		if(!strcmp(i->d_name,".")||!strcmp(i->d_name,".."))
			continue;
		strcpy(buf,folderPath);
		strcat(buf,"/");
		strcat(buf,i->d_name);
		
		struct stat M;
		stat(buf,&M);
		
		if(S_ISDIR(M.st_mode))
		{
			floor+=1;
			showDirStructure(buf);
			floor-=1;
		}
		else
		{
			if(S_ISREG(M.st_mode)){
				char ext[256];
				len=0;
				for(int j=strlen(buf)-1;buf[j]!='.';j--)
					ext[len++]=buf[j];
				ext[len]='\0';
				for(int j=0;j<len/2;j++){
					char t=ext[j];
					ext[j]=ext[len-1-j];
					ext[len-1-j]=t;
				}
				if(!strcmp(ext,"jpg")||!strcmp(ext,"png")||!strcmp(ext,"bmp")){
					for(int j=0;j<(floor+1)*2;j++)
						cout<<" ";
					cout<<"--"<<i->d_name<<endl;
				}
			}
		}
	}
	closedir(dir);
	
	/********** END **********/
}