本文所述實例代碼主要實現讀取給定路徑下的所有文件夾名稱或所有帶后綴的文件名的功能。具體解決方法如下:
主要用到了以下幾個頭文件(類):io.h, fstream, string。
首先,讀取某給定路徑下所有文件夾與文件名稱,并帶完整路徑。實現代碼如下:
void getAllFiles( string path, vector<string>& files) { //文件句柄 long hFile = 0; //文件信息 struct _finddata_t fileinfo; string p; if((hFile = _findfirst(p.assign(path).append("http://*").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("http://").append(fileinfo.name) ); getFilesall( p.assign(path).append("http://").append(fileinfo.name), files ); } } else { files.push_back(p.assign(path).append("http://").append(fileinfo.name) ); } }while(_findnext(hFile, &fileinfo) == 0); _findclose(hFile); } }
該函數有兩個參數,第一個為路徑字符串(string類型,最好為絕對路徑);第二個參數為文件夾與文件名稱存儲變量(vector類型,引用傳遞)。
在主函數中調用格式(并將結果保存在文件"AllFiles.txt"中,第一行為總數):
char * filePath = "E://YunShi"; vector<string> files; char * distAll = "AllFiles.txt"; getFilesall(filePath, files); ofstream ofn(distAll); int size = files.size(); ofn<<size<<endl; for (int i = 0;i<size;i++) { ofn<<files[i]<<endl; } ofn.close();
同理,只讀取某給定路徑下的當前文件夾名(以下類似,只給出函數,調用案例同上):
void getJustCurrentDir( string path, vector<string>& files) { //文件句柄 long hFile = 0; //文件信息 struct _finddata_t fileinfo; string p; if((hFile = _findfirst(p.assign(path).append("http://*").c_str(),&fileinfo)) != -1) { do { if((fileinfo.attrib & _A_SUBDIR)) { if(strcmp(fileinfo.name,".") != 0 && strcmp(fileinfo.name,"..") != 0) { files.push_back(fileinfo.name); //files.push_back(p.assign(path).append("http://").append(fileinfo.name) ); } } }while(_findnext(hFile, &fileinfo) == 0); _findclose(hFile); } }
只讀取某給定路徑下的當前文件名:
void getJustCurrentFile( string path, vector<string>& files) { //文件句柄 long hFile = 0; //文件信息 struct _finddata_t fileinfo; string p; if((hFile = _findfirst(p.assign(path).append("http://*").c_str(),&fileinfo)) != -1) { do { if((fileinfo.attrib & _A_SUBDIR)) { ; } else { files.push_back(fileinfo.name); //files.push_back(p.assign(path).append("http://").append(fileinfo.name) ); } }while(_findnext(hFile, &fileinfo) == 0); _findclose(hFile); } }
只讀取某給定路徑下的所有文件名(即包含當前目錄及子目錄的文件):
void getFilesAll( string path, vector<string>& files) { //文件句柄 long hFile = 0; //文件信息 struct _finddata_t fileinfo; string p; if((hFile = _findfirst(p.assign(path).append("http://*").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("http://").append(fileinfo.name) ); getFilesA( p.assign(path).append("http://").append(fileinfo.name), files ); } } else { files.push_back(p.assign(path).append("http://").append(fileinfo.name) ); } }while(_findnext(hFile, &fileinfo) == 0); _findclose(hFile); } }
新聞熱點
疑難解答
圖片精選