There is a plenty of questions on SO regarding this, but most of them do not mention writing wstring back to file. So for example I found this for reading:
// open as a byte stream
std::wifstream fin("/testutf16.txt", std::ios::binary);
// apply BOM-sensitive UTF-16 facet
fin.imbue(std::locale(fin.getloc(),
new std::codecvt_utf16<wchar_t, 0x10ffff, std::consume_header>));
// read
std::wstring ws;
for(wchar_t c; fin.get(c); )
{
std::cout << std::showbase << std::hex << c << '\n';
ws.push_back(c);
}
I tried similar stuff for writing:
std::wofstream wofs("/utf16dump.txt", std::ios::binary);
wofs.imbue(std::locale(wofs.getloc(),
new std::codecvt_utf16<wchar_t, 0x10ffff, std::consume_header>));
wofs << ws;
but it produces garbage, (or Notpad++ and vim cant interpret it). As mentioned in the title Im on Win, native C++, VS 2010.
Input file:
t€stUTF16✡
test
This is what is the result:
t€stUTF16✡
test
convert to hex:
0000000: 7400 ac20 7300 7400 5500 5400 4600 3100 t.. s.t.U.T.F.1.
0000010: 3600 2127 0d00 0a00 7400 6500 7300 7400 6.!'....t.e.s.t.
0000020: 0a
...
vim normal output:
t^@¬ s^@t^@U^@T^@F^@1^@6^@!'^M^@ ^@t^@e^@s^@t^@
EDIT: I ended up using UTF8. Andrei Alexandrescu says it is the best encoding so no big loss. :)