首页 > 解决方案 > 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 从文件中加载数据 - 我必须使用语言环境编解码器加载它。

标签: c++qtencoding

解决方案


推荐阅读