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/