Converting 'const char*' to 'LPCTSTR' for CreateDirectory

我的梦境 提交于 2019-12-06 13:05:36

std::string is a class that holds char-based data. To pass a std::string data to API functions, you have to use its c_str() method to get a char* pointer to the string's actual data.

CreateDirectory() takes a TCHAR* as input. If UNICODE is defined, TCHAR maps to wchar_t, otherwise it maps to char instead. If you need to stick with std::string but do not want to make your code UNICODE-aware, then use CreateDirectoryA() instead, eg:

#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;
}

To make this code TCHAR-aware, you can do this instead:

#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;
}

However, Ansi-based OS versions are long dead, everything is Unicode nowadays. TCHAR should not be used in new code anymore:

#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;
}

If you're not building a Unicode executable, calling c_str() on the std::string will result in a const char* (aka non-Unicode LPCTSTR) that you can pass into CreateDirectory().

The code would look like this:

CreateDirectory(FilePath.c_str(), NULL):

Please note that this will result in a compile error if you're trying to build a Unicode executable.

If you have to append to FilePath I would recommend that you either continue to use std::string or use Microsoft's CString to do the string manipulation as that's less painful that doing it the C way and juggling raw char*. Personally I would use std::string unless you are already in an MFC application that uses CString.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!