简体   繁体   English

C++ CreateDirectory() 不适用于 APPDATA

[英]C++ CreateDirectory() not working with APPDATA

I want to create a directory inside the %APPDATA% folder.我想在 %APPDATA% 文件夹中创建一个目录。 I am using CreateDirectory() for this and it doesn't work.我为此使用了 CreateDirectory() 但它不起作用。 I debugged the code and it seems like the path is correct, but I can't see a new directory in my the APPDATA.我调试了代码,看起来路径是正确的,但我在 APPDATA 中看不到新目录。

My code for creating dit in appdata:我在 appdata 中创建 dit 的代码:

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:这就是我对 function 的称呼:

setAppDataDir("thisistest");

I use Visual Studio 2019 and the debugger tells me, that path is C:\\Users\\Micha\AppData\Roaming\\thisistest我使用 Visual Studio 2019,调试器告诉我,该路径是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* ). CreateDirectory()是一个在您的情况下扩展为CreateDirectoryW()的宏,它需要 UTF-16LE 编码( wchar_t* )中的字符串。 You are casting the const char* path param to PCWSTR ( const wchar_t* ):您正在将const char* path参数转换为PCWSTR ( const wchar_t* ):

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

But you are not converting that string into a UTF-16LE string.但是您没有将该字符串转换为 UTF-16LE 字符串。

So, you need to convert your path into a wchar_t* string.因此,您需要将path转换为wchar_t*字符串。 There are some methods to do it, see Convert char * to LPWSTR .有一些方法可以做到这一点,请参阅将 char * 转换为 LPWSTR

The problem was the way I was giving path to CreateDirectory() .问题是我给CreateDirectory()路径的方式。 As @RemyLebeau pointed out, I should have used CreateDirectoryA() .正如@RemyLebeau 指出的那样,我应该使用CreateDirectoryA() This change solved the issue.此更改解决了该问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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