VS 32位上的文件遍历,在fileFolderPath下找fileExtension的文件。
vector<string> FindAllFile(const string fileFolderPath, const string fileExtension)
{
struct _finddata_t fileInfo; // 文件信息结构体
string fileFolder = fileFolderPath + "\\*." + fileExtension;
vector<string> fileName;
// 1. 第一次查找
long findResult = _findfirst(fileFolder.c_str(), &fileInfo);
if (findResult == -1)
{
_findclose(findResult);
return fileName;
}
// 2. 循环查找
string temp1 = "\\";
do
{
string temp;
temp = fileFolderPath.c_str() + temp1 + fileInfo.name;
//sprintf(fileName, "%s\\%s", fileFolderPath.c_str(), fileInfo.name);
if (fileInfo.attrib == _A_ARCH) // 是存档类型文件
{
fileName.push_back(temp);
}
} while (!_findnext(findResult, &fileInfo));
_findclose(findResult);
return fileName;
}
32位的资料很多,64位系统下的比较少,我用了这个在调用_findnext的时候容易报错。自己查了资料,写了个64位系统下的
#include <io.h>
#include <AtlBase.h>
std::string ws2s(const std::wstring& ws)
{
std::string curLocale = setlocale(LC_ALL, NULL); // curLocale = "C";
setlocale(LC_ALL, "chs");
const wchar_t* _Source = ws.c_str();
size_t _Dsize = 2 * ws.size() + 1;
char *_Dest = new char[_Dsize];
memset(_Dest, 0, _Dsize);
wcstombs(_Dest, _Source, _Dsize);
std::string result = _Dest;
delete[]_Dest;
setlocale(LC_ALL, curLocale.c_str());
return result;
}
std::wstring s2ws(const std::string& s)
{
setlocale(LC_ALL, "chs");
const char* _Source = s.c_str();
size_t _Dsize = s.size() + 1;
wchar_t *_Dest = new wchar_t[_Dsize];
wmemset(_Dest, 0, _Dsize);
mbstowcs(_Dest, _Source, _Dsize);
std::wstring result = _Dest;
delete[]_Dest;
setlocale(LC_ALL, "C");
return result;
}
vector<string> FindAllFile(const string path, const string fileExtension)
{
wstring wpath = s2ws(path);
LPCTSTR str = wpath.c_str();
_tfinddata64_t c_file;
intptr_t hFile;
TCHAR root[MAX_PATH];
_tcscpy(root, str);
_tcscat(root, _T("\\*."));
wstring wext = s2ws(fileExtension);
LPCTSTR str2 = wext.c_str();
_tcscat(root, str2);
hFile = _tfindfirst64(root, &c_file);
vector<string> filenames;
if (hFile == -1)
return filenames;
do
{
TCHAR *fullPath = new TCHAR[MAX_PATH];
_tcscpy(fullPath,str);
_tcscat(fullPath, _T("\\"));
_tcscat(fullPath, c_file.name);
if (c_file.attrib == _A_ARCH)
{
string file = ws2s(fullPath);
filenames.push_back(file);
}
}
while (_tfindnext64(hFile, &c_file) == 0);
//close search handle
_findclose(hFile);
return filenames;
}
参考 点击打开链接