#include "stdafx.h"
#include <string>
#include <windows.h>
using namespace std;
int main()
{
string FilePath = "C:\\Documents and Settings\\whatever";
CreateDirectory(FilePath, NULL);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
错误:错误 C2664:“CreateDirectory”:无法将参数 1 从“const char *”转换为“LPCTSTR”
std::string是一个保存基于数据的类char。要将std::string数据传递给 API 函数,您必须使用其c_str()方法来获取char*指向字符串实际数据的指针。
CreateDirectory()以 aTCHAR*作为输入。如果UNICODE已定义,TCHAR则映射到wchar_t,否则映射到char。如果您需要坚持std::string但不想让您的代码UNICODE感知,请改用CreateDirectoryA(),例如:
#include "stdafx.h"
#include <string>
#include <windows.h>
int main()
{
std::string FilePath = "C:\\Documents and Settings\\whatever";
CreateDirectoryA(FilePath.c_str(), NULL);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
要使此代码TCHAR具有感知能力,您可以这样做:
#include "stdafx.h"
#include <string>
#include <windows.h>
int main()
{
std::basic_string<TCHAR> FilePath = TEXT("C:\\Documents and Settings\\whatever");
CreateDirectory(FilePath.c_str(), NULL);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
然而,基于 Ansi 的操作系统版本早已消亡,现在一切都是 Unicode。 TCHAR不应再在新代码中使用:
#include "stdafx.h"
#include <string>
#include <windows.h>
int main()
{
std::wstring FilePath = L"C:\\Documents and Settings\\whatever";
CreateDirectoryW(FilePath.c_str(), NULL);
return 0;
}
Run Code Online (Sandbox Code Playgroud)