Sossenbinder
Sossenbinder

Reputation: 5312

How do I read multiple serialized objects of the same type out of a QDataStream?

I am currently trying to implement a serialization system in my code, which stores multiple objects of a type in a file. This works pretty well, I usually just append them one by one with the OpenMode QIODevice::Append. No problems here.

However, on the other side, when reading these objects, I run into trouble.

This is what it looks like right now:

file.open(QIODevice::ReadOnly);
QDataStream out(&file);
MyObject entry;
out >> entry;
entries.push_back(entry);

It works as expected, but it only reads in one element. However, I want to read all objects inside the file, not just the first one occuring.

How could this be done? I am pretty unsure whether there is a possibility for my stream to know the size my object is taking in the file while being in serialized form, but there has to be some way?

Upvotes: 1

Views: 487

Answers (1)

Ilya
Ilya

Reputation: 5557

Just iterate on the entire stream:

while( out.atEnd() == false ) {
  MyObject entry;
  out >> entry;
  entries.push_back(entry);  
}

Upvotes: 3

Related Questions