PDA

View Full Version : Problem using multiple QDataStreams



TheShow
18th November 2009, 18:59
I have a large array of floats and need to write sections of the array out to multiple files. The following code demonstrates an approach (that didn't work):



const int FILES = 8;
QVector<QDataStream> v;

for (int i=0; i<FILES; i++)
{
QString qstr("f");
qstr.append(QString::number(i));
qstr.append(".dat");
QFile f(qstr);
f.open(QIODevice::WriteOnly | QIODevice::Append);
QDataStream ds(&f);
v.append(ds);
}

for (int cnt=0; cnt<99; cnt++)
{
for (int i=0; i<FILES; i++)
{
QDataStream ds = v.at(i);
ds << 999.9; // test
}
}
for (int i=0; i<FILES; i++)
{
v.at(i).device().close();
}

This code gives the following compiler error:

QDataStream::QDataStream(const QDataStream&) is private

So, my solution was to replace the QVector<QDataStream> with pointers to QDataStream:




const int FILES = 8;
QVector<QDataStream *> v;

for (int i=0; i<FILES; i++)
{
QString qstr("f");
qstr.append(QString::number(i));
qstr.append(".dat");
QFile f(qstr);
f.open(QIODevice::WriteOnly | QIODevice::Append);
QDataStream *ds = new QDataStream(&f);
v.append(ds);
}

for (int cnt=0; cnt<99; cnt++)
{
for (int i=0; i<FILES; i++)
{
QDataStream *ds = v.at(i);
*ds << 999.9; // test
}
}
for (int i=0; i<FILES; i++)
{
v.at(i)->device()->close();
}


This compiled, but when it ran, the debugger stopped in qglobal.h at a line having something to do with QFlags. This is the line where it seems to break in qglobal.h:

inline QFlags operator&(Enum f) const { QFlags g; g.i = i & f; return g; }


I avoided this altogether by opening a QFile - QDataStream and writing values, then closing the stream each time within a loop. This worked but seems terribly inefficient.

Can someone demonstrate how to open and write to multiple binary files using QDataStream's operators?

wysota
18th November 2009, 20:57
You are creating files on the stack hence they are destroyed after you leave the iteration of the loop where they are created. Create them on heap as you do with QDataStreams.