Wrote to a file using std::wofstream. The file remained empty

江枫思渺然 提交于 2019-11-27 14:24:25
Artyom

In Visual studio the output stream is always written in ANSI encoding, and it does not support UTF-8 output.

What is basically need to do is to create a locale class, install into it UTF-8 facet and then imbue it to the fstream.

What happens that code points are not being converted to UTF encoding. So basically this would not work under MSVC as it does not support UTF-8.

This would work under Linux with UTF-8 locale

#include <fstream>
int main()
{
    std::locale::global(std::locale(""));
    std::wofstream fout("myfile");
    fout << L"Հայաստան Россия Österreich Ελλάδα भारत" << std::endl;
}

~ And under windows this would work:

#include <fstream>
int main()
{
    std::locale::global(std::locale("Russian_Russia"));
    std::wofstream fout("myfile");
    fout << L"Россия" << std::endl;
}

As only ANSI encodings are supported by MSVC.

Codecvt facet can be found in some Boost libraries. For example: http://www.boost.org/doc/libs/1_38_0/libs/serialization/doc/codecvt.html

MSVC offers the codecvt_utf8 locale facet for this problem.

#include <codecvt>

// ...  
std::wofstream fout(fileName);
std::locale loc(std::locale::classic(), new std::codecvt_utf8<wchar_t>);
fout.imbue(loc);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!