你好,我是新手。经过漫长的绝望搜索,我想发布这个问题:如何获得具有特定扩展名的驱动器中的所有文件的列表?
我正在开发一个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