Adrian Michałek
Adrian Michałek

Reputation: 49

Why GetFileAttributesA() works with unix directory path separators?

As in the above title question, my current working directory contains one directory "a" which contains another directory "b". The correct path to directory "b" is "a\b" (on Windows platform). Assuming that "/" is used as "switch" character I expect function GetFileAttributesA() to give an error for the specified path "a/b". The following documentation says nothing about additional internal path separator conversion.

The question is why GetFileAttributesA() works with unix path separators? The C++ code is (C++14):

#include <windows.h>
int main()
{
    DWORD gfa1 = GetFileAttributesA("a\\b");
    DWORD gfa2 = GetFileAttributesA("a/b");
    // Both gfa1 and gfa2 are equal to FILE_ATTRIBUTE_DIRECTORY
    // I expect the gfa2 to be INVALID_FILE_ATTRIBUTES
    return 0;
}

The reason why I would expect function to fail with "a/b" is simple. To simplify I have one function which tells if particular path is a directory for both Linux and Windows system. As long as the function has the same behaviour for slashes and backslashes on Windows I'm forced to add the same behaviour on Linux (separator conversion) or vice-versa (do not allow creating directories with "/" on Windows which is not supported by this function).

Upvotes: 1

Views: 297

Answers (1)

Fire Lancer
Fire Lancer

Reputation: 30145

Many parts of Windows accept both forward and backward slashes, including nearly all the file API's. Both slashes are reserved characters, and can not appear within a file or directory name.

I am not sure this is detailed in a central place, but for the file API's, the Naming Files, Path, and Namespaces document has this to say:

File I/O functions in the Windows API convert "/" to "\" as part of converting the name to an NT-style name, except when using the "\?\" prefix as detailed in the following sections.

As for:

Assuming that "/" is used as "switch" character

Since on the command line any file or directory path containing a space must be quoted, you can safely split such a path with forward slashes from any switches/parameters on that space character or quotation rules. Similar to how there is no issue with - being in file and directory names, but also used by many programs for command line switches.

Upvotes: 2

Related Questions