c++ - QString 类中的 toLocal8bit 方法安全吗?
问题描述
我有一个没有 BOM 编码的 UTF-8 文件。我必须从该文件加载数据(只有一行)并将其保存在 QString 变量中。接下来我必须将此数据从 QString 变量转换为其他 QString,但使用 UTF-8 编码。所以我有:
QFile file(R"(C:\Users\tom\Desktop\myFile.txt)");
file.open(QIODevice::ReadOnly);
QTextStream textStream(file.readAll());
textStream.setCodec(QTextCodec::codecForLocale());
QString stringVar = textStream.readLine();
...
QTextStream textStream2(stringVar.toLocal8Bit(), QIODevice::ReadOnly);
textStream2.setCodec(QTextCodec::codecForName("UTF-8"));
QString stringVar2 = textStream2.readLine();
它有效。但在toLocal8bit()
文档中有一段文字:
Returns the local 8-bit representation of the string as a QByteArray. The returned byte
array is undefined if the string contains characters not supported by the local 8-bit encoding.
在 windows-1250(我的语言环境编解码器)编码中,我们有 251 个字符(251 / 256)。我尝试过的情况是,当我在文件中有一个包含一个字节的 2 字节字符时,在 windows-1250 ( 0x81 ) 和 qDebug 显示'Ă\u0081',当我显示 stringVar 和下一个正确的字符时,我显示 stringVar2 . 一切都好。所以在我的情况下使用 toLocal8bit() 是安全的吗?
编辑:我无法使用 UTF-8 从文件中加载数据 - 我必须使用语言环境编解码器加载它。
解决方案
推荐阅读
- html - 当我在笔记本电脑(小屏幕)上打开网页时,网页会变形,但在台式电脑(大屏幕)上打开它时仍然可以)
- apache-spark - 使用python将databricks数据帧写入S3
- java - 更正应用程序的类路径,使其包含一个兼容的 javax.persistence.Table 版本
- dynamics-nav - 我们如何在 NAV 2016 中使用 C/AL 执行 CRUD 和 Join 操作?
- python - 我不能在生成器中使用其他人的模型来生成我的输入。我该如何解决?
- python - 比较来自多个数据帧的数据帧以过滤数据并提取相关特征
- sql-server - 更改 sql server 表问题
- c++ - 我不明白如何使用嵌套循环计算每个可能子数组的总和
- javascript - 无法理解 .reduce 在 JavaScript 中的工作原理
- java - 我们已经在 selenium 的 Chrome 中设置了下载目录。但是下载控制默认会自动下载到下载文件夹