如何在不使用 C++ 中的宽字符串的情况下创建目录?
How do I create a directory without using wide strings in C++?
我正在尝试创建一个目录以便将文件放入其中。
我的代码:
string Set;
...
CreateDirectory("Game/Sets/" + Set, NULL); // I'm trying to have something like this. CreateDirectory needs wide strings, but Set is narrow.
变量Set
是一个窄字符串。
我想我可能需要 CreateDirectory
以外的东西,但我不知道是什么。
你必须使用 string::c_str()
成员函数来获取相应的 const char*
(AKA LPCSTR
):
string Set;
...
CreateDirectory(("Game/Sets/" + Set).c_str(), NULL);
但使用临时变量可能更好:
string Set;
...
string fullDir = "Game/Sets/" + Set;
CreateDirectory(fullDir.c_str(), NULL);
您可能正在编译一个 UNICODE 程序。如果是这种情况,您将收到错误消息,因为 const char*
无法转换为 const wchar_t*
。解决办法是调用ANSI版本的函数:
CreateDirectoryA(fullDir.c_str(), NULL);
如果您愿意,即使没有错误也可以使用 ANSI 函数,只是为了更加一致。
请记住,CreateDirectory
实际上是一个根据项目配置扩展为 CreateDirectoryW
或 CreateDirectoryA
的宏。您可以根据需要使用这三个名称中的任何一个。
我正在尝试创建一个目录以便将文件放入其中。
我的代码:
string Set;
...
CreateDirectory("Game/Sets/" + Set, NULL); // I'm trying to have something like this. CreateDirectory needs wide strings, but Set is narrow.
变量Set
是一个窄字符串。
我想我可能需要 CreateDirectory
以外的东西,但我不知道是什么。
你必须使用 string::c_str()
成员函数来获取相应的 const char*
(AKA LPCSTR
):
string Set;
...
CreateDirectory(("Game/Sets/" + Set).c_str(), NULL);
但使用临时变量可能更好:
string Set;
...
string fullDir = "Game/Sets/" + Set;
CreateDirectory(fullDir.c_str(), NULL);
您可能正在编译一个 UNICODE 程序。如果是这种情况,您将收到错误消息,因为 const char*
无法转换为 const wchar_t*
。解决办法是调用ANSI版本的函数:
CreateDirectoryA(fullDir.c_str(), NULL);
如果您愿意,即使没有错误也可以使用 ANSI 函数,只是为了更加一致。
请记住,CreateDirectory
实际上是一个根据项目配置扩展为 CreateDirectoryW
或 CreateDirectoryA
的宏。您可以根据需要使用这三个名称中的任何一个。