PDA

View Full Version : serialising reading writing



TheKedge
5th April 2007, 14:35
Sorry if this is a silly question:

I've got a (very simple) class with lots of member variables. It's more like a 'struct' with a clear() function.
I want to get all the member variables written into a file (and later have the file read in again). I thought I might define operators '<<' and '>>' for the class.
But I still don't quite see it. That won't help my QDataStream, will it?

Instead, should I write a 'serialise(QDataStream& out)' and a 'QDataStream serialise()'
or 'QByteArray serialise()' and 'serialise(QByteArray)' and then write/read that to/from the file?

thanks
K

high_flyer
5th April 2007, 14:45
I am not sure I understand what you want.
But if you just want to serialize data in to a file then you don't need much, Qt has this out of the box for regular types (int,float,etc.. and QTypes) :


QFile *file = new QFile("file.dat");
QDataStream os(file);
if(file->open(QIODevice::Append)
{
os<<myClass->m_someRegularTypeVar;
}



You can overlard the global QDataStream::operator<<() and >>() if you need to serialize custom types.

TheKedge
5th April 2007, 15:19
Yep, thanks, that has answered it.

The question was basically even simpler.

I have 50 member variables, and don't want to use << in big lists when I need to write save the class interna. So I could:
a) overload the QDataStream
or
b) have some member function taking a QDataStream&

I think I'll choose (b)
thanks again

K

fullmetalcoder
5th April 2007, 16:36
a) overload the QDataStream
Just create a new handler :


QDataStream& operator << (QDataStream& out, MyStruct *s)
{
// serialization code goes here
}

QDataStream& operator >> (QDataStream& in, MyStruct *s)
{
// deserialization code goes here
}


:)

TheKedge
5th April 2007, 17:17
Ahhhh!
brilliant, understood.
thanks
K