tags:

views:

112

answers:

4

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

Any Ideas?

+2  A: 

Use T2A macro for that.

sharptooth
A: 

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.

sbi
+1  A: 

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));
}
Philipp
TTBOMK, it's not guaranteed that `wofstream` will write UTF-16. IIRC, the Dinkumware implementation will write (and read, FTM) UTF-8.
sbi
Thanks a lot, It worked very well :)
Mohammad Abdelaziz
@sbi: Yes, I already noticed that on Linux. C++ streams just suck. To write UTF-16 reliably, you really seem to need to use an `ofstream` to prevent the brain-dead char conversion of C++, and use `reinterpret_cast`. If the Dinkumware library uses UTF-8, fine, at least not some completely insane choice like Windows-1252.
Philipp
A: 

here you are! http://stackoverflow.com/questions/342772/lptstr-to-char

Chandler