c++ - GetFileAttributes 因绝对路径而失败

标签 c++ winapi

<分区>

我正在用 WinAPI 编写一个简单的程序来检查目录是否存在,这是功能代码:

BOOL directoryExists( LPCSTR path ) {
    DWORD pathAttributes = GetFileAttributes ( path );

    return pathAttributes != INVALID_FILE_ATTRIBUTES 
                  && pathAttributes == FILE_ATTRIBUTE_DIRECTORY;
 }

然后我在我的 main 中用这行代码测试它:

 std::cout << ( ( directoryExists( "C:\\Users\\Admin\\Desktop" ) ?  
                          "Directory found"  : "Directory not found"  ) 
          << static_cast< char >( 0xA );

看起来无论我尝试输入什么绝对路径,我都会得到“找不到目录”。不管怎样,相对路径都会成功!

我哪里失败了? :|

提前致谢!

最佳答案

GetFileAttributes 的返回值是一个位域,不是一个单一的值,每个文件属性常量都包含一个位掩码,所以你应该这样检查它:

return (INVALID_FILE_ATTRIBUTES != pathAttributes) 
              && (0 != (pathAttributes & FILE_ATTRIBUTE_DIRECTORY));

您还应该使用 GetFileAttributesW 和宽字符路径,因为 GetFileAttributesA 无法处理 Unicode 路径。

关于c++ - GetFileAttributes 因绝对路径而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43423800/

相关文章:

c++ - 获取两个字符串之间的字符串

c++ - Go 编程语言会取代 C++ 吗?

windows - 设置透明背景 Win32

c# - 当保护模式打开时,DeleteURLCacheEntry 不会删除临时 Internet 文件

c++ - 为什么 GetProcessImageFileName 返回 null 而不是进程的地址?

c++ - 如何用 C 语言实现基于 xml 的结构化语言的解析器?

C++ 将数组传递给函数错误 : incompatible types in assignment

windows - 如何使用 Delphi 在 Windows 中从 USB 驱动器挂载分区?

windows - 为什么 Unicode Windows 标题栏(仅)是问号(?)代码点?

c++ - 使用 C++ 和 WinAPI 将 WM_DROPFILES 发送到第三方应用程序