c++ - GetFileAttributesA 为现有目录返回 "17"。 "16"表示它是一个目录,文档中没有提到 "17"

标签 c++ windows winapi mingw constants

Windows 7 64 位,用 mingw 编译。我正在尝试使用 Windows header 中的 GetFileAttributesA 来测试给定路径是否是目录。作为目录的常量是 16。但出于某种原因,它返回 17。我的代码如下所示:

#include <iostream>
#include <windows.h>

void dir_exists(std::string dir_path)
{
    DWORD f_attrib = GetFileAttributesA(dir_path.c_str());
    std::cout << "Current: " << f_attrib << std::endl <<
        "Wanted: " <<
        FILE_ATTRIBUTE_DIRECTORY << std::endl;
}

int main()
{
    dir_exists("C:\\Users\\");
    return 0;
}

当我运行它时,输出是:

Current: 17  
Wanted: 16

电流应该返回 16,在这里。正如我在主题中所说,我什至在文档中找不到任何提及 17 的含义。

最佳答案

GetFileAttributes 返回位掩码,其有效值列于此处:File Attribute Constants .

17 == 0x11,也就是说返回值为
FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY

如果你只是想检测你的路径是否指向一个目录,用 FILE_ATTRIBUTE_DIRECTORY 屏蔽返回值并查看它是否非零:

#include <string>
#include <iostream>
#include <windows.h>

bool dir_exists(std::string const& dir_path)
{
    DWORD const f_attrib = GetFileAttributesA(dir_path.c_str());
    return f_attrib != INVALID_FILE_ATTRIBUTES &&
           (f_attrib & FILE_ATTRIBUTE_DIRECTORY);
}

int main()
{
    std::cout << dir_exists("C:\\Users\\") << '\n';
}

关于c++ - GetFileAttributesA 为现有目录返回 "17"。 "16"表示它是一个目录,文档中没有提到 "17",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13058892/

相关文章:

windows - 如果加载它的 DLL 被卸载,DLL 是否会被删除?

c++ - std::vector 和多维数组的连续内存

c++ - 不能在 if 语句中直接使用 void func 将字符串转换为大写 - C++

windows - 我可以在 Linux 上生成带有原生 Excel 图表的 Excel 文件吗?

windows - Git:在 Windows 中协调两个具有重复名称(大小写不同)的文件夹,同时保留历史记录

windows - 在 Windows 上构建 Clang : DiagnosticCommonKinds. inc header 不存在

c++ - 串口通讯初始化

c++ - 获取函数成员地址

c++ - 纯虚函数重载

c++ - 如何使用Visual Studio C++将2个列表框添加到1个窗口中?