C++獲得資料夾下所有檔案的路徑及檔名
阿新 • • 發佈:2019-02-05
標頭檔案:#include< io.h >
filePath:資料夾路徑
vector<string> files;
////獲取該路徑下的所有檔案
getFiles(filePath, files ); //函式
char str[30];
int size = files.size();
for (int i = 0;i < size;i++)
{
cout<<files[i].c_str()<<endl;
}
……
void getFiles( 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) getFiles( 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); } }