我有一个使用UTF-8编码的文本文件,我正在使用简单的方法来读取它:
ifstream in("test.txt");
我想创建一个新文件,使其采用UTF-8编码或Unicode。我该如何使用ofstream
或其他方法实现?当前代码创建的是ANSI编码。
ofstream out(fileName.c_str(), ios::out | ios::app | ios::binary);
我有一个使用UTF-8编码的文本文件,我正在使用简单的方法来读取它:
ifstream in("test.txt");
我想创建一个新文件,使其采用UTF-8编码或Unicode。我该如何使用ofstream
或其他方法实现?当前代码创建的是ANSI编码。
ofstream out(fileName.c_str(), ios::out | ios::app | ios::binary);
好的,关于便携式变量。如果您使用C++11
标准(因为有许多附加包括"utf8"
的内容,可以永久解决此问题),那么很容易。
但是如果您想要使用旧标准的多平台代码,您可以使用以下方法使用流进行编写:
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();
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...