简体   繁体   中英

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?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM