_findnext64 因访问冲突而崩溃

_findnext64 crashed with access violation

我正在尝试获取具有特定通配符扩展名的所有文件,例如“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 作为返回值 intptr_t。如果您有 64 位版本,intptr_t 是 64 位宽。您将结果存储在 long 中 - 只有 32 位宽,因此截断了返回的句柄。

如果您将代码编写为:

       const auto hFile = _findfirst64(pathstr, &c_file);
       if (hFile != -1)

那么这就不是问题了。

(我也会将 pathstr 构造为 std::string 并使用 .c_str() 来获取指针。我讨厌固定大小的数组。)