#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下的第一个默认文件,一般是".",就是当前目录,第二个是"..",上一级目录,在循环中判断时可以过滤掉的,而其他的子目录和文件也可以被递归获取到完整的名称。加上文件后缀可以对想搜索的文件进行过滤。