c++ - 驱动器号上的 FindFiles 失败但通过路径

标签 c++ windows api winapi

我正在使用下面的代码

#include "stdafx.h"
#include <iostream>
#include "stdafx.h"
#include <windows.h>
#include <string>
#include <commdlg.h>
#include <Shlwapi.h>
#pragma comment (lib, "Shlwapi.lib")

// This function is an abomination -- I just wrote it to be quick.
std::wstring CombinePaths(std::wstring const &pattern, LPCWSTR filename) {
    std::wstring tmp(pattern);
    tmp.push_back('\0');
    PathRemoveFileSpec(&tmp[0]);
    std::wstring retVal(MAX_PATH, '\0');
    PathCombine(&retVal[0], tmp.c_str(), filename);
    return retVal.c_str();
}

void FindFiles(std::wstring const &pattern) {
    WIN32_FIND_DATA fd;
    HANDLE h = FindFirstFile(pattern.c_str(), &fd);
    if (h == INVALID_HANDLE_VALUE) {
        wprintf(L"FindFirstFile.  Err=%d\n", GetLastError());
        return;
    }

    do {
        std::wstring fullPath = CombinePaths(pattern, fd.cFileName);
        wprintf(L"FullPath=%s\n", fullPath.c_str());
    } while (FindNextFile(h, &fd));

    FindClose(h);
}

int main()
{
    FindFiles(L"c:\\Windows"); //Passes
    FindFiles(L"c:\\"); //Fails
    std::cin.get();
    return 0;
}

为什么它不通过 C:\\ ?有什么建议吗?

最佳答案

来自FindFirstFile()文档:

HANDLE WINAPI FindFirstFile(
  _In_  LPCTSTR           lpFileName,
  _Out_ LPWIN32_FIND_DATA lpFindFileData
);

Parameters

lpFileName [in]

The directory or path, and the file name. The file name can include wildcard characters, for example, an asterisk (*) or a question mark (?).

This parameter should not be NULL, an invalid string (for example, an empty string or a string that is missing the terminating null character), or end in a trailing backslash ().

(强调我的)

这意味着您根本无法将 C:\ 作为参数传递并期望它起作用。

也就是说,您不应该使用 FindFirstFile() 来检查目录是否存在。这有点像用 12 号口径的霰弹 Gunicorn 死一只蚊子:它有效,但杀伤力太大了​​。

GetFileAttributes()是您应该使用的功能。

关于c++ - 驱动器号上的 FindFiles 失败但通过路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50417907/

相关文章:

c++ - 在调试期间提供 C++ 代码集值

windows - 如何通过 Windows 10 中的批处理脚本获取特定适配器的 ipv4 地址

Javascript - 保护 API key

ios - 发布参数未从应用程序到达 API

java - 在多用户环境中使用 hibernate 更新运行平衡

c++ - 如何获取指针数组中的元素数?

c++ - 为什么discard的参数是unsigned long long类型的?

c++ - MinGW 找不到 XInput.h header

windows - Visual Studio 2010 安装项目 - 64 位和 32 位的一个项目

windows - BATCH文件可通过SSH连接到Linux。如何?