开发者

Convert LPTSTR to string or char * to be written to a file

I want to convert LPT开发者_如何学GoSTR to string or char * to be able to write it to file using ofstream.

Any Ideas?


Use T2A macro for that.


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.

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.

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


IIUC, LPTSTTR might point to a char string or a wchar_t string, depending on a preprocessor directive. If that's right, then you need to switch between std::ofstream and std::wofstream, depending on that preprocessor directive.
Have a look at this answer. It deals with switching between console streams, depending on TCHAR, but the scheme is easily adapted to be used with file streams as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜