Qt+ICU识别文本文件编码并合并导出文本
核心部分
识别文本编码,这里使用ICU
核心代码
/// <summary>
/// 读取文本文件内容并返回QString
/// </summary>
/// <param name="path">文件路径</param>
/// <returns>文本内容</returns>
static QString readFile(QString path) {
// icu识别字符编码
UErrorCode status = U_ZERO_ERROR;
UCharsetDetector* detector = ucsdet_open(&status);
if (U_FAILURE(status)) {
return "";
}
// 读取文件内容
QFile file(path);
if (!file.open(QIODevice::ReadOnly)) {
return "";
}
QByteArray data = file.readAll();
file.close();
// 识别字符编码
ucsdet_setText(detector, data.data(), data.size(), &status);
if (U_FAILURE(status)) {
return "";
}
const UCharsetMatch* match = ucsdet_detect(detector, &status);
if (U_FAILURE(status)) {
return "";
}
const char* charset = ucsdet_getName(match, &status);
if (U_FAILURE(status)) {
return "";
}
// 转换编码
QTextCodec* codec = QTextCodec::codecForName(charset);
QString text = codec->toUnicode(data);
// 释放资源
ucsdet_close(detector);
return text;
}
示例
示例源代码
https://github.com/WindSnowLi/ExportSource
作者:Esofar
出处:https://www.cnblogs.com/WindSnowLi/p/16998150.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
2021-09-20 偶遇排序算法