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/