3

Windows 7 64 ビット、mingw でコンパイル。Windows ヘッダーで 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

Current は 16 を返すはずです。トピックで述べたように、ドキュメントで 17 が何を意味するかについての言及を見つけることさえできません。

4

1 に答える 1

11

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';
}
于 2012-10-24T22:40:25.517 に答える