Some Thing Wrong When I Save QString To File With Unicode Bom ?



  • Hi, I want to save QString to file with the Unicode Bom, like the following Code

    #include <QCoreApplication>
    
    #include <QString>
    #include <QFile>
    #include <QTextStream>
    #include <QDebug>
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
        QString str = QString::fromUtf8("你好,我是QString");
        QFile file;
        QTextStream out;
    
        file.setFileName("a.txt");
        if( !file.open( QIODevice::WriteOnly | QIODevice::Text) )
        {
            qDebug() << file.errorString();
            return 0;
        }
    
        out.setDevice(&file);
        out.setCodec("UTF-8");
        out.setGenerateByteOrderMark(true);
        out << str;
        file.close();
        qDebug() << "OK!";
    
        return a.exec();
    }
    

    But, when i use the vim :%!xxd to see the hex. I am not found the 0xffef.

    Maybe there is a better way to save QString to file with unicode and bom x0ffef ?



  • @joeQ

    oh, I know what i wrong! if i want to save file with x0ffef, i should use the 'utf-16'.

    #include <QCoreApplication>
    
    #include <QString>
    #include <QFile>
    #include <QTextStream>
    #include <QDebug>
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
        QString str = QString("你好,我是QString");
        QFile file;
        QTextStream out;
    
        file.setFileName("a.txt");
        if( !file.open( QIODevice::WriteOnly | QIODevice::Text) )
        {
            qDebug() << file.errorString();
            return 0;
        }
    
        out.setDevice(&file);
        out.setCodec("UTF-16"); ///< hould use the utf-16
        out.setGenerateByteOrderMark(true);
        out << str;
        file.close();
        qDebug() << "OK!";
    
        return a.exec();
    }
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.