在C++ 中读取文件夹下的文件名,如果存在子文件夹,递归读取子文件下的文件名
1 #include <fstream> 2 #include <iostream> 3 #include <string> 4 #include <sstream> 5 #include <vector> 6 #include <io.h> 7 8 using namespace std; 9 void getAllFiles(string path, vector<string>& files, string postfix) 10 { 11 // file handle 12 long hFile = 0; 13 // file info. struct 14 struct _finddata_t fileinfo; 15 string pathp; 16 if ((hFile = _findfirst(pathp.assign(path).append("\\*").c_str(), &fileinfo)) != -1) 17 { 18 do 19 { 20 if ((fileinfo.attrib & _A_SUBDIR)) // is folder? 21 { 22 // is folder 23 if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0) 24 { 25 //files.push_back(p.assign(path).append("/").append(fileinfo.name));//saving folder name 26 getAllFiles(pathp.assign(path).append("/").append(fileinfo.name), files, postfix);//find postfix file recursively 27 } 28 } 29 else //not folder 30 { 31 string filestr = fileinfo.name; 32 string prepostfix = "." + postfix; 33 int idx = filestr.find(prepostfix); 34 string poststr = filestr.substr(idx, filestr.size()); 35 if (0 == poststr.compare(prepostfix)) 36 files.push_back(pathp.assign(path).append("/").append(fileinfo.name)); 37 38 } 39 } while (_findnext(hFile, &fileinfo) == 0); //find next 40 _findclose(hFile); 41 } 42 } 43 //测试 44 void main() 45 { 46 string basedir = "D:/video/t/"; 47 string savingname = "filename.txt"; 48 49 string postfix = "hik"; // specify postfix 50 vector<string> files; 51 52 getAllFiles(basedir, files, postfix); 53 54 int filenum = files.size(); 55 56 // saving as txt file 57 ofstream outfilestream(savingname); // output file stream 58 outfilestream << filenum << endl; 59 for (int i = 0; i < filenum; i++) 60 { 61 outfilestream << files[i] << endl; 62 } 63 outfilestream.close(); 64 }