在Qt中创建UTF-8文件 [英] Create UTF-8 file in Qt

查看:745
本文介绍了在Qt中创建UTF-8文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Qt中创建UTF-8编码文件.

I'm trying to create a UTF-8 coded file in Qt.

#include <QtCore>

int main()
{
    QString unicodeString = "Some Unicode string";
    QFile fileOut("D:\\Temp\\qt_unicode.txt");
    if (!fileOut.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        return -1;
    }

    QTextStream streamFileOut(&fileOut);
    streamFileOut.setCodec("UTF-8");
    streamFileOut << unicodeString;
    streamFileOut.flush();

    fileOut.close();

    return 0;
}

我认为,当QString默认为Unicode且将输出流的编解码器设置为UTF-8时,我的文件将为UTF-8.但是不是,而是ANSI. 我做错了什么?我的琴弦有问题吗?您可以更正我的代码以创建UTF-8文件吗? 对我来说,下一步是读取ANSI文件并将其另存为UTF-8文件,因此我将必须对每个读取的字符串执行转换,但是现在,我想从一个文件开始. 谢谢.

I thought when QString is by default Unicode and when I set codec of the output stream to UTF-8 that my file will be UTF-8. But it's not, it's ANSI. What do I do wrong? Is something wrong with my strings? Can you correct my code to create UTF-8 file? Next step for me will be to read ANSI file and save it as UTF-8 file, so I'll have to perform a conversion on each read string but now, I want to start with a file. Thank you.

推荐答案

您的代码绝对正确.在我看来,唯一可疑的部分是:

Your code is absolutely correct. The only part that looks suspicious to me is this:

QString unicodeString = "Some Unicode string";

您确实意识到,您不能只将Unicode字符串放在引号中,对吗?默认情况下,QString使用Latin1,因此,如果它只是带有重音符号的字符,则可能还不错,但是最好使用UTF-8对源进行编码并执行以下操作:

You do realize, that you can't just put a Unicode string in quotes, do you? By default QString uses Latin1, so if it just about accented characters, you're probably fine, but better to have your source encoded in UTF-8 and do this:

QString unicodeString = QString::fromUtf8("Some Unicode string");

这将适用于任何可以想象的语言.使用QObject :: trUtf8()更好,因为它为您提供了许多i18n功能.

This will work for any imaginable language. Using QObject::trUtf8() is even better as it gives you a lot of i18n capabilities.

修改

虽然确实生成了正确的UTF-8文件,但是如果您希望记事本将文件识别为UTF-8,则完全不同.您需要在其中放置BOM.可以按照其他答案中的建议进行操作,也可以采用以下另一种方式:

While it's true that you generate a correct UTF-8 file, if you want Notepad to recognize your file as UTF-8, it's a different story. You need to put a BOM in there. It can be done either as suggested in another answer, or here is another way:

streamFileOut.setGenerateByteOrderMark(true);

这篇关于在Qt中创建UTF-8文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆