c++fileunicodemfcwofstream

How can I print a Unicode CString (in Japanese) to a text file?


This seems like a tough one for me. I have this code that prints out a CString to a text file, but the value happens to be in Unicode (Japanese). As soon as this line is hit, nothing else below it gets printed.

Any idea how can I print the Japanese text in the text file?

#define OFSTREAM std::wofstream

OFSTREAM *outfile;
outfile = new OFSTREAM;
outfile->open (filename, ios::out);

CString varName = _T(" ");
/*stuff*/
*outfile << _T("  Name: ") << (LPCTSTR)varName << _T("\n");

Solution

  • The reason the stream stops working is because the fail bit gets set. You're not handling the error so the stream stops working. The fail bit needs to be cleared when errors happen.

    The locale on the wostream object must be set such that the codecvt facet handles converting the Japanese wide characters into bytes. By default the "C" locale is used which in VS will only support ASCII characters. If you only need writing the file to work on Japanese versions of Windows you can do:

    std::wofstream outfile(filename, ios::out);
    outfile.imbue(std::locale("")); // use the system locale
    
    CString varName = _T(" ");
    /*stuff*/
    outfile << L"  Name: " << (LPCTSTR)varName << L"\n";
    

    Or you can specify the Japanese locale on Windows:

    outfile.imbue(std::locale("Japanese")); // use the japanese locale on any Windows system
    

    Both of these methods use the legacy Japanese locale encoding, which should probably be avoided. You can instead use UTF-8:

    // replace just the codecvt facet of the stream's current locale
    outfile.imbue(std::locale(outfile.getloc(), new std::codecvt_utf8_utf16<wchar_t>()));