如何连接字符* 和 LPWSTR 字符串

How to concatenate char* and LPWSTR string?

本文关键字:LPWSTR 字符串 字符 何连接 连接      更新时间:2023-10-16

我想使用MoveFile函数,这个函数使用两个LPWSTR参数,但我有一个char*和LWSTR,如何连接它们?

//move file
    LPWSTR latestFile = L"test.SPL";
    char*  spoolFolder = "C:\Windows\System32\spoolPRINTERS\";
    LPWSTR fileToMove = spoolFolder + latestFile;
    BOOL moved = MoveFile(latestFile, L"C:\UnprocessedFiles\" + latestFile);

只是为了澄清,LPWSTR 是 wchar_t* 的 typedef。您可以使用wcscat_s来连接此形式的字符串。您的一个char*字符串应该更改为相同的类型,因为您将其作为简单的文字存在(只需在文字前面加上L并更改声明的类型)。但是,由于您将其标记为C++,因此您可以使用 std::wstring 类更轻松地完成所有这些操作。

std::wstring latestFile = wstring("test.SPL");
std::wstring spoolFolder = wstring("C:\Windows\System32\spoolPRINTERS\");
std::wstring fileToMove = spoolFolder + latestFile; 
BOOL moved = MoveFile(latestFile.c_str(), fileToMove.c_str());

实际上,LPWSTR只是w_char*的一个典型。 因此,如果您咨询 MSDN,您将看到:

typded wchar_t* LPWSTR;

这里的 w_char* 表示您的字符串将被编码为 UNICODE 而不是 ANSI 方案。因此,在Windows下,UNICODE字符串将是UTF16字符串(每个字符2个字节)。

std::wstring 也是 std::basic_string <wchar_t,char_traits<>> 的 typedef,所以通过将你的输入声明为 wstring 并调用 wasting.c_str() 这将完成这些工作。