#include <io.h>
#include <stdio.h>
void getFiles(string path, vector<string>& files, string postfix)
{
//文件句柄
long hFile = 0;
//文件信息
struct _finddata_t fileinfo;
string p;
if ((hFile = _findfirst(p.assign(path).c_str(), &fileinfo)) != -1)
{
do
{
//如果是目錄,迭代之
//如果不是,加入列表
if ((fileinfo.attrib & _A_SUBDIR))
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
getFiles(p.assign(path).append("\\*"), files, postfix);
}
else
{
if (postfix.size() == 0 || (postfix.size() > 0 && (postfix.c_str(), strchr(fileinfo.name, '.'))))
files.push_back(p.assign(fileinfo.name));
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}
void main()
{
vector<string> files;
getFiles("testvideo", files, ".jpg|.avi");
}
網上的代碼明顯有問題,在遞歸的時候用"path\\path"進行遞歸搜索,顯然第一次遞歸就失敗啊,有可能是最早放出代碼的小夥伴故意的,結果很多人也不試,拿來就用。
遞歸的時候用"path\\*"可以檢索出path下的第一個默認文件,一般是".",就是當前目錄,第二個是"..",上一級目錄,在循環中判斷時可以過濾掉的,而其他的子目錄和文件也可以被遞歸獲取到完整的名稱。加上文件後綴可以對想搜索的文件進行過濾。