I want to convert LPTSTR to string or char * to be able to write it to file using ofstream.
Any Ideas?
I want to convert LPTSTR to string or char * to be able to write it to file using ofstream.
Any Ideas?
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.
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));
}
here you are! http://stackoverflow.com/questions/342772/lptstr-to-char