我试图获取具有特定通配符扩展名(例如“ right_*.jpg
”)的所有文件,但这些代码在运行时因“ access violation
”而崩溃。这是针对x64构建的。
int GetDir64(const char *dir, const char *str_wildcard, std::vector<std::string> &files)
{
char pathstr[500];
struct __finddata64_t c_file;
long hFile;
sprintf(pathstr, "%s\\%s", dir, str_wildcard);
printf("GetDir(): %s\n", pathstr);
if ((hFile = _findfirst64(pathstr, &c_file)) != -1L)
{
do
{
std::string fn_str = std::string(c_file.name);
files.push_back(fn_str);
} while (_findnext64(hFile, &c_file) == 0); // this is where the crash happened
_findclose(hFile);
}
return 0;
}
最佳答案
返回的所有_findfirst
函数都是documented。如果您使用的是64位版本,则intptr_t
为64位宽。您将结果存储在一个long中-只有32位宽,因此会截断返回的句柄。
如果您将代码编写为:
const auto hFile = _findfirst64(pathstr, &c_file);
if (hFile != -1)
那么这将不是问题。
(我还将pathstr构造为
intptr_t
并使用std::string
获取指针。我讨厌固定大小的数组。)