Search code examples
c++stringc++11wstring

Write a std::u16string to file?


I am trying to write a std::u16string to file
It can easily be done with std::string

// ... pseudocode
std::wofstream outfile;
outfile.open("words.txt", std::ios_base::app);
outfile << "something"; 
outfile.close();
// ...

But how can I write a std::u16string to file?

Thanks


Solution

  • You need to create a basic_ofstream whose char type is equivalent to the u16string value type, which should be char16_t:

    typedef std::basic_ofstream<char16_t> u16ofstream;
    
    u16ofstream outfile("words.txt", std::ios_base::app);
    outfile << someu16string; 
    outfile.close();
    

    Alternatively, you can convert the u16string to a regular string and just write it to a plain ofstream, but you'll have to handle the conversion and deal with the string's encoding on your own.

    wofstream may also be compatible with u16string on some platforms (specifically Windows), but it's not portable.