c ++如何在unicode / utf8中写/读流 [英] c++ how to write/read ofstream in unicode / utf8
问题描述
我有ut8文本文件,使用简单的读取:
I have ut8 text file , that im reading using simple :
ifstream in("test.txt");
现在我喜欢创建一个新的文件wll的ut8编码或Unicode
如何这是与流或其他?
这会创建我ansi编码。
now i like to create new file that wll be ut8 encoding or Unicode how can i do this with ofstream or other ? this creates me ansi Encoding.
ofstream out(fileName.c_str(), ios::out | ios::app | ios::binary);
推荐答案
这很容易,如果你使用 C ++ 11
标准(因为有很多额外的包括像utf8
,这永远解决这个问题)。
Ok, about the portable variant. It is easy, if you use the C++11
standard (because there are a lot of additional includes like "utf8"
, which solves this problem forever).
但如果您想使用旧版标准的多平台代码,可以使用此方法用流写入:
But if you want to use multi-platform code with older standards, you can use this method to write with streams:
- 阅读关于流的UTF转换器的文章
- 从上方的来源将
stxutif.h
添加到您的项目 -
以ANSI模式打开文件并将BOM添加到文件的开头,如下所示:
- Read the article about UTF converter for streams
- Add
stxutif.h
to your project from sources above Open the file in ANSI mode and add the BOM to the start of a file, like this:
std::ofstream fs;
fs.open(filepath, std::ios::out|std::ios::binary);
unsigned char smarker[3];
smarker[0] = 0xEF;
smarker[1] = 0xBB;
smarker[2] = 0xBF;
fs << smarker;
fs.close();
然后将文件打开为 UTF
并将您的内容写在那里:
Then open the file as UTF
and write your content there:
std::wofstream fs;
fs.open(filepath, std::ios::out|std::ios::app);
std::locale utf8_locale(std::locale(), new utf8cvt<false>);
fs.imbue(utf8_locale);
fs << .. // Write anything you want...
这篇关于c ++如何在unicode / utf8中写/读流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!