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 国际」许可协议进行许可。

posted @   WindSnowLi  阅读(44)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2021-09-20 偶遇排序算法
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
点击右上角即可分享
微信分享提示