[Interest] reading from and writing to a file with QDataStream

Sina Dogru sinadooru at gmail.com
Mon Mar 7 16:24:41 CET 2016


Tony and William,

My sincere thanks for your answer, it really helped me understand the issue
and saved my day :).

By the way here is the final code,

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

int main()
{
    QFile file("file.dat");

    file.open(QIODevice::WriteOnly);
    QByteArray bai;
    {
        // module A creates a byte array
        QDataStream out(&bai, QIODevice::WriteOnly);
        out << QString("A QString"); // writes some information on it
    }
    int len = bai.size();
    file.write(reinterpret_cast<char *>(&len), sizeof(len));
    file.write(bai);

    // and module B starts
    if (file.isOpen())
        file.close();
    file.open(QIODevice::ReadOnly);

    QString str;
    int a;                  // extracts size information
    file.read(reinterpret_cast<char *>(&a), sizeof(a));
    QDataStream in(file.read(a));
    in >> str;

    qDebug() << str << a; // output: "A QString" 22
    return 0;
}

Sina.

2016-03-07 17:11 GMT+02:00 william.crocker at analog.com <
william.crocker at analog.com>:

> On 03/07/2016 09:35 AM, Sina Dogru wrote:
>
>> Well but, I am writing a QString to QByteArray,
>>
>> QByteArray bai;
>> QDataStream out(&bai, QIODevice::WriteOnly);
>> out << QString("A QString");
>>
>> And writing an 'int' and QByteArray which a QString written
>>
>> file.open(QIODevice::WriteOnly);
>> QDataStream out2(&file); // and module A write those datas to a file.
>> out2 << bai.size();
>> out2 << bai;
>>
>>
> All I care about is the QDataStream.
>
> You wrote the size() of QByteArray (which may or may not be an int)
> and then you read an int.
>
> You wrote a QByteArray and then you read a QString.
> I do not care what is in the QByteArray which you wrote.
>
> You should read back a QByteArray and then, in a subsequent
> operation, extract the QString from that.
>
>
> I might screwed totally? :S
>>
>>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20160307/249484a3/attachment.html>


More information about the Interest mailing list