PDA

View Full Version : QDataStream data into QByteArray



bnosam
21st July 2014, 17:50
I am saving the contents of several variables using QDataStream.




out << objWidth << "\n" << objHeight << "\n";



Where objWidth and objHeight are a single byte (unsigned char, value from 0 to 255).

then it outputs another series of bytes from a vector



for(int i = 0; i < objWidth; i++)
{
for(int j = 0; j < objHeight; j++)
{
byte value = getCellValue(i, j);
out << value << ",";
}
}


Then it does it again after separating data with a new line character with another vector of data, the exact same dimensions, only different data, but same statement.

so the whole file would look like:



objWidth
\n
objHeight
\n
Vector1 data each element separated with a comma
\n
Vector2 data each element separated with a comma

Now when I read this data back from a file using QDataStream, do I want to process it directly from a file, or read it into QByteArray so I can process it there, removing new lines and commas etc?

Which is easier?

yeye_olive
21st July 2014, 18:03
You seem to expect a text file format. Shouldn't you be using QTextStream instead?

Regardless of whether you use a QDataStream or a QTextStream, you need not load everything in a QByteArray. You can read from any QIODevice, including a QFile. Just remember to call status() to detect failures.

bnosam
21st July 2014, 18:42
You seem to expect a text file format. Shouldn't you be using QTextStream instead?

Regardless of whether you use a QDataStream or a QTextStream, you need not load everything in a QByteArray. You can read from any QIODevice, including a QFile. Just remember to call status() to detect failures.

I would ordinarily go with a textformat for this, since it seems easily enough, but further on later, I'm going to be saving an image directly with the file, so I should use QDataStream for this file, correct? OR is there another easier way to do it?

ChrisW67
21st July 2014, 21:06
If this data is being written for the same (or another) Qt program to read then you might be better off using QDataStream to serialise the QVector and QImage/QPixmap etc. As it is you are not really using much of the capability of QDataStream so you could possibly just use the basic QIODevice functions to read() and write(). Use QFile or QBuffer for from-disk or in-memory data respectively.

As it is now you will likely have a jumble of printable and non-printable chars in the file. If you want an on-disk format you can read in a text editor you are better off with QTextStream. When you write the image base 64 encode it so you get printable characters only.