使用std::ofstream配合std::string可跨平台处理UTF-8文件,Linux/macOS原生支持,Windows需避免宽字符流并手动处理BOM,推荐Boost.Locale等库实现可靠Unicode I/O。

在C++中处理Unicode或UTF-8编码的文件I/O,不能直接使用标准的
std::ifstream
std::ofstream
std::string
UTF-8是Unicode的一种变长编码方式,兼容ASCII,在Linux/macOS中常作为默认文本编码。但在Windows上,传统C++文件流默认使用本地编码(如GBK或CP1252),而不是UTF-8,这会导致读写中文等非ASCII字符出错。
如果你的文本文件是以UTF-8保存的(常见于跨平台项目),需要确保读写时不被错误地转码。
在Linux/macOS上,文件系统通常原生支持UTF-8,可以直接用
std::ofstream
立即学习“C++免费学习笔记(深入)”;
std::string
示例代码:
#include <fstream>
#include <string>
int main() {
std::ofstream out("utf8.txt");
out << "Hello 世界\n"; // 假设源码为UTF-8
out.close();
return 0;
}
只要终端或编辑器支持UTF-8,内容就能正确显示。
Windows的
std::ofstream
\n
\r\n
std::wofstream
要可靠写入UTF-8,建议:
std::wofstream
std::ofstream
std::string
若需读取含BOM的UTF-8文件,可手动跳过前3个字节:
std::ifstream in("utf8_with_bom.txt", std::ios::binary);
if (in) {
char bom[3];
in.read(bom, 3);
if (!(bom[0] == '\xEF' && bom[1] == '\xBB' && bom[2] == '\xBF')) {
in.seekg(0); // 没有BOM,重置
}
}
对于复杂场景(如读写UTF-16、转换编码),推荐使用成熟库:
使用Boost.Locale读取UTF-8文件示例:
#include <boost/locale.hpp>
#include <fstream>
#include <iostream>
int main() {
using namespace boost::locale;
generator gen;
std::locale::global(gen(""));
std::wifstream in("text.txt");
in.imbue(std::locale("")); // 使用系统UTF-8 locale
std::wstring line;
while (std::getline(in, line)) {
std::wcout << line << L"\n";
}
}
注意:需确保系统支持UTF-8 locale(如Linux下"en_US.UTF-8")。
基本上就这些。只要坚持用
std::string
以上就是C++如何在文件I/O中处理Unicode或UTF-8编码的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号