简体   繁体   中英

QT Reading binary file and then convert it to QString

I saved the QString in the file like this:

QString str="blabla";
QByteArray _forWrite=QByteArray::fromHex(str.toLatin1());
f.write(_forWrite); // f is the file that is opened for writing.

Then when I read the file I use QFile::readAll() to take the QByteArray but I don't know how to convert it to QString.

I tried to use the constructor that uses QByteArray but It didn't work out. I tried also with QByteArray::data() but same result. What I do wrong ?

It's not clear why you are calling QByteArray::fromHex at all. toLatin1() already return you QByteArray where each symbol encoded with one byte.

[ UPDATE ]

You should NOT call QByteArray::fromHex at all, because:

invalid characters in the input are skipped

And invalid characters are characters that are not the numbers 0-9 and the letters af

You can use QDataStream

#include <QApplication>

#include <QDataStream>
#include <QByteArray>
#include <QFile>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

        QString strToWrite = "blabla";
        QFile fileToWrite("file.bin");
        QDataStream dataStreamWriter(&fileToWrite);
        fileToWrite.open(QIODevice::WriteOnly);
        dataStreamWriter << strToWrite;
        fileToWrite.close();

        QString strToRead = "";
        QFile fileToRead("file.bin");
        QDataStream dataStreamReader(&fileToRead);
        fileToRead.open(QIODevice::ReadOnly);
        dataStreamReader >> strToRead;
        fileToRead.close();

        qDebug() << strToRead;

    return app.exec();
}

Output : "blabla"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM