你好,我是新手。經過漫長的絕望搜索,我想發佈這個問題:如何獲得具有特定擴展名的驅動器中的所有文件的列表?
我正在開發一個C++程序,遞歸遍歷所有搜索特定文件類型的文件夾和子文件夾。
首先功能FindFiles(string, string, bool)
工作像一個魅力,但它的第二種形式FindFiles(struct var)
不能正常工作:它不會遍歷所有文件夾和子文件夾。
事實上,我需要第二種形式,因爲由於搜索可能太長,我需要使用API CreateThread
創建線程,並將我的arguments struct
作爲LPVOID
傳遞給它。
#include <windows.h>
#include <string>
#include <iostream>
using namespace std;
// Arguments struct
struct args{
string strDir;
string strFilter;
bool bRecurse;
};
void FindFiles(string strDir, string strFilter, bool bRecurse);
void FindFiles(args);
int main(){
// FindFiles("D:", "*.mp3", true); // works fine
args ar;
ar.bRecurse = true;
ar.strDir = "D:";
ar.strFilter = "*.mp3";
FindFiles(ar); // doesn't work fine
cout << endl;
return 0;
}
void FindFiles(string strDir, string strFilter, bool bRecurse = true){
if(bRecurse)
FindFiles(strDir, strFilter, false);
strDir += "\\";
WIN32_FIND_DATA wfd;
string strFileFilter = strDir + (bRecurse ? "*" : strFilter);
HANDLE hFile = FindFirstFile(strFileFilter.c_str(), &wfd);
if(INVALID_HANDLE_VALUE == hFile)
return;
else{
if(!bRecurse)
cout << strDir + string(wfd.cFileName) << endl;
while(FindNextFile(hFile, &wfd)){
if(!bRecurse)
cout << strDir + string(wfd.cFileName) << endl;
else{
if((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) > 0 &&
wfd.cFileName[0] != '.')
FindFiles(strDir + string(wfd.cFileName), strFilter, true);
}
}
// FindClose(hFile);
}
}
void FindFiles(args ar){
if(ar.bRecurse){
ar.bRecurse = false;
FindFiles(ar);
}
ar.strDir += "\\";
WIN32_FIND_DATA wfd;
string strFileFilter = ar.strDir + (ar.bRecurse ? "*" : ar.strFilter);
HANDLE hFile = FindFirstFile(strFileFilter.c_str(), &wfd);
if(INVALID_HANDLE_VALUE == hFile)
return;
else{
if(!ar.bRecurse)
cout << ar.strDir + string(wfd.cFileName) << endl;
while(FindNextFile(hFile, &wfd)){
if(!ar.bRecurse)
cout << ar.strDir + string(wfd.cFileName) << endl;
else{
if((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) > 0 &&
wfd.cFileName[0] != '.'){
ar.strDir += string(wfd.cFileName);
ar.bRecurse = true;
FindFiles(ar);
}
}
}
FindClose(hFile);
}
}
請看看第二個表格,因爲它是我的。我認爲那裏有一些愚蠢的錯誤。
任何幫助我真的很感激它。
@RemyLebeau:其實第一種形式,我發現它的地方在互聯網上,從而可以看到我編輯它作爲第二種形式。但是,如果你建議我一些替代品,那麼我真的很感激它。感謝名單! – WonFeiHong
你正在嘗試*方式*太難。使用[recursive_directory_iterator](https://docs.microsoft.com/en-us/cpp/standard-library/recursive-directory-iterator-class)爲您完成這項工作。此外,在本地使用Unicode的文件系統上對文件名使用ANSI/MBCS編碼是一個錯誤。 – IInspectable
@IInspectable:可以解釋更多關於錯誤的信息。 Thanx爲有用的鏈接。 – WonFeiHong