1. 程式人生 > >C++獲取資料夾下所有檔名稱的三種方式

C++獲取資料夾下所有檔名稱的三種方式

1

利用dos命令把資料夾下所有檔名存入指定檔案,再從檔案讀取,存入vector中

         string imglist_file = "test_result\\imglist.txt";//儲存檔名稱列表
	string temp_imgname;
	string dir_command("dir ");
	dir_command += m_strImageSet + "/b > " + imglist_file;//m_strImageSet是我之前建立的變數 裡面存放的是資料夾路徑
	ifstream file(imglist_file.c_str(),ios::in);
	system(dir_command.c_str());
	vector <string> imglist;

	//把影象名稱都存入vector中
           while(file>>temp_imgname)
	{
	     imglist.pushback(temp_imgname);
	}
	file.close();
		

2

利用_findfirst、_findnext獲取所有檔名

         string temp_imgname;
	long   hFile   =   0;//檔案控制代碼
	_finddata_t fileinfo;//檔案資訊
          vector<string> imglist	
	if((hFile = _findfirst(m_strImageSet+"\\*",&fileinfo)) !=  -1)//m_strImageSet是我之前建立的變數 裡面存放的是資料夾路徑
	{
		do
		{
			if((fileinfo.attrib &  _A_SUBDIR))
			{
				continue;//如果是目錄則跳過
			}
			else
			{
				imglist.push_back(temp_imgname);
			}
		}while(_findnext(hFile, &fileinfo)  == 0);
	
		_findclose(hFile);
	}


3 利用finder獲取

         WIN32_FIND_DATA FindFileData;
	int finder = 1;
	CString m_strImageSet_t = m_strImageSet +"\\*.*";)//m_strImageSet是我之前建立的變數 裡面存放的是資料夾路徑
	CString m_strImageSet_t1 = m_strImageSet +"\\";
         string imgname_temp;
         vector <string> imglist;
 	HANDLE hFind = FindFirstFile(m_strImageSet_t, &FindFileData);
	if (hFind == INVALID_HANDLE_VALUE)
	{
		printf ("Invalid File Handle. GetLastError reports %d\n", GetLastError ());
		return ;
	}
	else
	{  
		while(finder)
		{

			if((_tcscmp(FindFileData.cFileName,_T("."))==0)||(_tcscmp(FindFileData.cFileName,_T(".."))==0))//過濾資源管理器中預設兩個資料夾.和..
			{
				finder = FindNextFile(hFind,&FindFileData);  
				continue;
			}
			else
                           {
				temp_imgname = FindFileData.cFileName; 
				imglist.pushback(temp_imgname);
				 
			}
			
			
		}
	}
	FindClose(hFind);