Question

I have a function that is used to creating a directory. It uses CreateDirectoryA()

CreateDirectory reports that it failed but when I check the error code using GetLastError() it reports that ERROR_SUCCESS

code:

BOOL isDirCreated = CreateDirectoryA(dirName.c_str(), NULL);
DWORD dw = GetLastError();
if (isDirCreated) {
        if (!SetFileAttributesA(dirName.c_str(), attributes)) {
            printf("SetFileAttributes() %s failed with (%d)", dirName.c_str(), GetLastError()));
            return;
        }
    } else {
        printf("CreateDirectory() %s Failed with (%d)", dirName.c_str(), dw));
        if(ERROR_ALREADY_EXISTS != dw) {
            return;
        }
    }

This returns: (multiple calls to the function)

CreateDirectory() testDir Failed with (0)
CreateDirectory() testDir\dir Failed with (183)

Even though CreateDirectoryA returns false the directory is created. The failure always happens for the first call to the function. All subsequent calls work as expected.

Any ideas why CreateDirectory would be returning false when it is successfully creating the directory.

Here is a similar post but the solution does not work for me:

ReadFile() says it failed, but the error code is ERROR_SUCCESS

UPDATE It turns out this error was caused because another header that was included in the code had a function "GetLastError" the other function was in a separate namespace so the solution was to call GetLastError as follows.

/*
 * the :: will tell it to use the GetLastError that is available on the global 
 * scope.  Most of Microsoft's calls don't have any namespace.
 */
DWORD dw = ::GetLastError();
Was it helpful?

Solution

It turns out this error was caused because another header that was included in the code had a function "GetLastError" the other function was in a separate namespace so the solution was to call GetLastError as follows.

/*
 * the :: will tell it to use the GetLastError that is available on the global 
 * scope.  Most of Microsoft's calls don't have any namespace.
 */
DWORD dw = ::GetLastError();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top