PDA

View Full Version : Output a QVector of doubles to a binary file (without using QDatastream)



OzQTNoob
7th April 2016, 08:00
okay so i once (a long time ago) had some code I wrote that let me write binary output files but I have lost it and cant remember how to get it working. After much trawling I am now asking for help.

So if i have a QVector<double> how can I write this to a binary file?

I know I need QFile and QByteArray (and possibly reinterpret_cast) and size_of(double) but I don't know how to put it together properly. Its driving me nuts and I am sure its probably rather simple.

Cheers

ChrisW67
7th April 2016, 10:25
If you do not need to worry about byte order then something like:


QVector<double> vec(1000, 0.0);
QFile file("output.bin");
if (file.open(QIODevice::WriteOnly) {
qint64 bytesWritten = file.write(static_cast<const char*>(vec.constData()), sizeof(double) * vec.size());
}

OzQTNoob
8th April 2016, 02:47
Hi Chris,

you've come to my rescue once again. I still use the code snippets you provided for reading binary data :)

Am I right in assuming that the byte order problem is only if i go from a PC to unix (little to big) but if i am staying in the little endian environment then its not a problem? I wont be swapping environments for what its worth.

Cheers
Andrew

Added after 19 minutes:

Hi again Chris,

i got the following on compilation
error: invalid static_cast from type 'const double*' to type 'const char*'
qint64 bytesWritten = outputFile.write(static_cast<const char*>(atmosParams.constData()), sizeof(double)*atmosParams.size());

atmosParams is a QVector equivalent to the vec QVector used in the example snippet. Had a quick flick around and changed static_cast to reinterpret_cast and all worked.

Due to my lack of knowledge here I presume its probably all okay :)
^

Radek
8th April 2016, 07:36
(1) Endianity relates to CPUs, not to operating systems. It does not matter whether PC or Unix, it matters whether, for example, Intel or Motorola.
(2) Yes, reinterpret cast, not static cast. reinterpret cast simply changes the pointer meaning (from const double * to const char *) without bothering of the actual data at the pointer (and that's why it is considered dangerous but it is okay here). static cast tries to convert.