最近在工作中,需要获取指定文件夹下的所有文件名,参考所查文件,写了个函数,在本地能成功。但编译打版,在服务器报错。
最终调试发现,在win10中,使用文件遍历函数_findnext会报0xC0000005错误
原因:
_findnext()第一个参数”路径句柄”,返回的类型为intptr_t(long long),如果定义为long,在win7中是没有问题,但是在win10中就要改为long long或者intptr_t
static void getFiles(string path, vector<string>& files)
{
//文件句柄
long hFile = 0;
//文件信息,声明一个存储文件信息的结构体
struct _finddata_t fileinfo;
string p;//字符串,存放路径
if ((hFile = _findfirst(p.assign(path).append("/*").c_str(), &fileinfo)) != -1)//若查找成功,则进入
{
do
{
//如果是目录,迭代之(即文件夹内还有文件夹)
if ((fileinfo.attrib & _A_SUBDIR))
{
//文件名不等于"."&&文件名不等于".."
//.表示当前目录
//..表示当前目录的父目录
//判断时,两者都要忽略,不然就无限递归跳不出去了!
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
getFiles(p.assign(path).append("/").append(fileinfo.name), files);
}
//如果不是,加入列表
else
{
files.push_back(p.assign(path).append("/").append(fileinfo.name));
}
} while (_findnext(hFile, &fileinfo) == 0);
//_findclose函数结束查找
_findclose(hFile);
}
}
方案一:修改参数类型 long ---> intptr_t
intptr_t hFile = 0;
方案二:采用boost库函数
#include <boost/filesystem.hpp>
static void getFiles(string path, vector<string>& files)
{
using namespace boost::filesystem;
if (exists(path) && is_directory(path))
{
recursive_directory_iterator it(path);
recursive_directory_iterator end;
for (; it != end; ++it)
{
if (!is_directory(it->path()))
{
files.push_back(it->path().string());
}
}
}
}