1

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 ?

2
  • What do you mean "didn't work out"? Compilation error? Runtime error? Runtime OK but garbled data? Commented Oct 1, 2014 at 16:05
  • Why are you using fromHex on a string that is not hexadecimal? :-/ That is invalid input and not checked, so it won't do what you think. Commented Oct 1, 2014 at 16:06

2 Answers 2

2

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 a-f

Sign up to request clarification or add additional context in comments.

3 Comments

The string is definitely blabla with lowercase L, as in "blah blah", not "b one a b one a". One shouldn't be calling "fromHex" with that as input. So there's definitely a misunderstanding here.
Yes, I just updated the answer with the reason why calling of toHex() doesn't work.
Yes that was it. I used toHex because I saw an example that used it didn't realise that toLatin1() returns QByteArray. Thanks!
1

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"

2 Comments

Thank you but I wanted without QDataStream :)
QString s = "blabla"; QByteArray ba = s.toUtf8(); QString s2 = QString::fromUtf8(ba); OR QByteArray ba = s.toLatin1(); QString s2 = QString::fromLatin1(ba); Depends on the character set you will use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.