【问题标题】:Windows file API CloseHandle function throws an exception: "An invalid handle was specified"Windows 文件 API CloseHandle 函数引发异常:“指定了无效句柄”
【发布时间】:2014-12-19 13:01:41
【问题描述】:

我已经编写了函数(在 MS VS 2013 中的 Visual C++ 中)与 on 不同

Recursively searching for files in the computer

下面是我的函数源代码:

wstring FolderPathValidator::FindRequiredFolder(const wstring& p_InitialPath, wstring p_RequiredFolderName)
{
    wstring foundFolder = L"";
    wstring folderPath = p_InitialPath + L"\\*";
    WIN32_FIND_DATAW folderInfo;
    HANDLE search_handle = FindFirstFileW(folderPath.c_str(), &folderInfo);
    if (search_handle != INVALID_HANDLE_VALUE)
    {
        vector<wstring> folders;

        do
        {
            if (folderInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                if ((!lstrcmpW(folderInfo.cFileName, L".")) || (!lstrcmpW(folderInfo.cFileName, L"..")))
                    continue;
            }

            folderPath = p_InitialPath + L"\\" + wstring(folderInfo.cFileName);

            if (folderInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                if (folderInfo.cFileName == p_RequiredFolderName)
                {
                    foundFolder = folderInfo.cFileName;
                    return foundFolder;
                }
                folders.push_back(folderPath);
            }
        } while (FindNextFileW(search_handle, &folderInfo));

        CloseHandle(search_handle);

        for (vector<wstring>::iterator iter = folders.begin(), end = folders.end(); iter != end; ++iter)
            FindRequiredFolder(*iter, p_RequiredFolderName);
    }

    return foundFolder;
}

该功能开始正常工作。但是当它尝试执行该行时

CloseHandle(search_handle);

然后出现以下异常:

First step of exception handling on address 0x76D712C7 в WordsCounter.exe: 0xC0000008: An invalid handle was specified.

其中“WordsCounter”是应用程序可执行文件的名称。 FindRequiredFolder 函数是 FolderPathValidator 类的成员。 FolderPathValidator 类位于静态类库项目中。两个项目:类库和使用该库的 C++ 控制台应用程序都在同一个解决方案中。在文件和文件夹名称中,有时会出现西里尔字母的俄语名称。但我不认为西里尔文文件夹或文件名是此错误的原因。这个错误的原因是什么?我该如何纠正?请帮忙。

【问题讨论】:

  • Offtopic:使用 if ( (folderInfo.dwFileAttributes &amp; FILE_ATTRIBUTE_DIRECTORY) != 0 ) 代替 if (folderInfo.dwFileAttributes &amp; FILE_ATTRIBUTE_DIRECTORY)。这将在某些情况下防止编译器警告。

标签: winapi exception visual-c++


【解决方案1】:
  1. 使用FindClose 而不是CloseHandle。您在哪里读到必须使用 CloseHandle?

  2. 使用 T() 或 TEXT() 宏,代替 L" 前缀用于 unicode 字符串 (TEXT( "" ))。

  3. 使用lstrcmp 而不使用W。如果您的项目是 Unicode,它是宏并调用 lstrcmpW。

【讨论】:

  • 23 与问题无关。无论您是明确使用 Unicode API(带有 W 后缀)和带有 L 前缀的字符串文字,还是带有未指定 API 版本(即没有 AW 后缀)的 _T-macro编码约定、项目目标和个人品味的问题。只要您匹配 API 调用和字符串文字编码。代码在这方面很好。
  • 好的,23 是后记。 1 是问题的答案。
  • 感谢 FindClose 的帮助!
  • 我不同意 2 和 3。但是,不能争论 1。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-09
  • 1970-01-01
  • 2011-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多