Sherlock Holmes
Sherlock Holmes

Reputation: 291

C++ CreateDirectory() not working with APPDATA

I want to create a directory inside the %APPDATA% folder. I am using CreateDirectory() for this and it doesn't work. I debugged the code and it seems like the path is correct, but I can't see a new directory in my the APPDATA.

My code for creating dit in appdata:

void setAppDataDir(std::string name)
{
    char* path;
    size_t len;
    _dupenv_s(&path, &len, "APPDATA");
    AppDataPath = path;
    AppDataPath += "\\"+name;

    createDir(this->AppDataPath.c_str());
}

void createDir(const char* path)
{
    assert(CreateDirectory((PCWSTR)path, NULL) || ERROR_ALREADY_EXISTS == GetLastError()); // no exception here
}

This is how I call the function:

setAppDataDir("thisistest");

I use Visual Studio 2019 and the debugger tells me, that path is C:\\Users\\Micha\AppData\Roaming\\thisistest

What am I doing wrong?

Upvotes: 0

Views: 642

Answers (2)

Dmitry Sokolov
Dmitry Sokolov

Reputation: 3190

CreateDirectory() is a macro that expands to CreateDirectoryW() in your case, which requires strings in UTF-16LE encoding (wchar_t*). You are casting the const char* path param to PCWSTR (const wchar_t*):

CreateDirectory((PCWSTR)path, NULL) ...

But you are not converting that string into a UTF-16LE string.

So, you need to convert your path into a wchar_t* string. There are some methods to do it, see Convert char * to LPWSTR.

Upvotes: 1

Sherlock Holmes
Sherlock Holmes

Reputation: 291

The problem was the way I was giving path to CreateDirectory(). As @RemyLebeau pointed out, I should have used CreateDirectoryA(). This change solved the issue.

Upvotes: 0

Related Questions