将LPTSTR转换为要写入文件的字符串或char * [英] Convert LPTSTR to string or char * to be written to a file

查看:363
本文介绍了将LPTSTR转换为要写入文件的字符串或char *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将LPTSTR转换为字符串或char *,以便能够使用ofstream将其写入文件。

I want to convert LPTSTR to string or char * to be able to write it to file using ofstream.

任何想法?

推荐答案

在其他线程中呈现的大多数解决方案不必要地转换为过时的编码,而不是Unicode编码。只需使用 reinterpret_cast 即可写入UTF-16文件或使用 WideCharToMultiByte

Most solutions presented in the other threads unnecessarily convert to an obsolete encoding instead of an Unicode encoding. Simply use reinterpret_cast<const char*> to write UTF-16 files, or convert to UTF-8 using WideCharToMultiByte.

要离开问题,使用 LPTSTR 而不是 LPWSTR 现在没有什么意义,因为旧的9x系列的Windows是完全过时和不支持。只需使用 LPWSTR 和随附的宽字符(即UTF-16代码单元)类型 WCHAR

To depart a bit from the question, using LPTSTR instead of LPWSTR doesn't make much sense nowadays since the old 9x series of Windows is completely obsolete and unsupported. Simply use LPWSTR and the accompanying "wide character" (i.e., UTF-16 code unit) types like WCHAR or wchar_t everywhere.

这里是一个例子(我希望)写UTF-16或UTF-32(后者在Linux / OS X上):

Here is an example that (I hope) writes UTF-16 or UTF-32 (the latter on Linux/OS X):

#include <fstream>
#include <string>

int main() {
  std::ofstream stream("test.txt");  // better use L"test.txt" on Windows if possible
  std::wstring string = L"Test\n";
  stream.write(reinterpret_cast<const char*>(string.data()), string.size() * sizeof(wchar_t));
}

这篇关于将LPTSTR转换为要写入文件的字符串或char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆