1. 程式人生 > >圖片檢視器(c++)

圖片檢視器(c++)

第3關:圖片檢視器

挑戰任務

參加“綠盟杯”競賽的小明想要開發一個圖片檢視器,他想只顯示資料夾下所有圖片型別的檔案。

你來幫小明實現這個功能吧。

程式設計要求

基本功能與第二題類似,程式設計實現對給定資料夾目錄結構的展示,如果是資料夾則在其名字之前加上+--若是檔案則加上--,上級目錄與下級目錄、下級檔案用兩個空格作為間隔,同級下依照資料夾、檔案的首字母順序依次列印;另外需要對檔案進行過濾,只顯示圖片型別的檔案,本關需要過濾的圖片檔案型別有:“jpg,png,bmp”,請補充完善右側程式碼區中的showDirStructure(char *folderPath)函式實現本關要求的功能,其中函式引數含義如下:

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

測試說明

樣例1

輸入:src/step3/root

輸出:

提示:

你可以通過如下連結下載本關涉及到的目錄檔案:

https://www.educoder.net/attachments/download/202620/step3Dir.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 **********/
}