_findnext64因访问冲突而崩溃

时间:2019-01-24 15:41:14

标签: c++ windows 64-bit

我正在尝试获取所有带有特定通配符扩展名的文件,例如“ 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;
    }

1 个答案:

答案 0 :(得分:3)

所有_findfirst函数都是documented返回intptr_t。如果您使用的是64位版本,则intptr_t的宽度为64位。您将结果存储在一个长整数中,该整数只有32位宽,因此会截断返回的句柄。

如果您将代码编写为:

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

那么这将不是问题。

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