使用C++獲取資料夾中所有檔名(windows環境)
阿新 • • 發佈:2019-01-01
由於經常有讀取一個資料夾中的很多隨機編號的檔案,很多時候需要讀取某些特定格式的所有檔案。
下面的程式碼可以讀取指定檔案家中的所有檔案和資料夾中格式為jpg的檔案
windows平臺程式碼:
#if 1 #include <io.h> #include <fstream> #include <string> #include <vector> #include <iostream> using namespace std; //獲取所有的檔名 void GetAllFiles( string path, vector<string>& files) { long hFile = 0; //檔案資訊 struct _finddata_t fileinfo; string p; if((hFile = _findfirst(p.assign(path).append("\\*").c_str(),&fileinfo)) != -1) { do { if((fileinfo.attrib & _A_SUBDIR)) { if(strcmp(fileinfo.name,".") != 0 && strcmp(fileinfo.name,"..") != 0) { files.push_back(p.assign(path).append("\\").append(fileinfo.name) ); GetAllFiles( p.assign(path).append("\\").append(fileinfo.name), files ); } } else { files.push_back(p.assign(path).append("\\").append(fileinfo.name) ); } }while(_findnext(hFile, &fileinfo) == 0); _findclose(hFile); } } //獲取特定格式的檔名 void GetAllFormatFiles( string path, vector<string>& files,string format) { //檔案控制代碼 long hFile = 0; //檔案資訊 struct _finddata_t fileinfo; string p; if((hFile = _findfirst(p.assign(path).append("\\*" + format).c_str(),&fileinfo)) != -1) { do { if((fileinfo.attrib & _A_SUBDIR)) { if(strcmp(fileinfo.name,".") != 0 && strcmp(fileinfo.name,"..") != 0) { //files.push_back(p.assign(path).append("\\").append(fileinfo.name) ); GetAllFormatFiles( p.assign(path).append("\\").append(fileinfo.name), files,format); } } else { files.push_back(p.assign(path).append("\\").append(fileinfo.name) ); } }while(_findnext(hFile, &fileinfo) == 0); _findclose(hFile); } } // 該函式有兩個引數,第一個為路徑字串(string型別,最好為絕對路徑); // 第二個引數為資料夾與檔名稱儲存變數(vector型別,引用傳遞)。 // 在主函式中呼叫格式(並將結果儲存在檔案"AllFiles.txt"中,第一行為總數): int main() { string filePath = "D:\\projects\\WSD\\EBI\\samples\\2013WSD\\BottleBottom\\"; vector<string> files; char * distAll = "AllFiles.txt"; //讀取所有的檔案,包括子檔案的檔案 //GetAllFiles(filePath, files); //讀取所有格式為jpg的檔案 string format = ".bmp"; GetAllFormatFiles(filePath, files,format); ofstream ofn(distAll); int size = files.size(); ofn<<size<<endl; for (int i = 0;i<size;i++) { ofn<<files[i]<<endl; cout<< files[i] << endl; } ofn.close(); return 0; } #endif