[Solved] Writing double to file using QDataStream?
-
I have a 2D array of doubles which I would like to store to a file in binary format. I understand that QDataStream is the required class for that. This is my current code:
@void FileString::SaveBinary()
{
if(dataStream)//QDataStream *dataStream
{
QString line = "MyApp 1.1.1.1";
*dataStream << line << '\n';
line.setNum(n);//int n
*dataStream << line << '\n';for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) *dataStream << array1[i][j];//double **array1 *dataStream << array2[i];//double *array2 *dataStream << "\n"; } line = "EOF"; *dataStream << '\n' << line; } QThread *thr = QThread::currentThread(); disconnect(thr, 0, this, 0); this->moveToThread(mainThread);//mainThread = GUI thread thr->exit(0);//
}@
SaveBinary is a SLOT run on a different thread than the GUI thread.
I am concerned that if this file is opened on a different hardware then it may fail.
So I would like to know what would be a better way to write double to a file and the file can be opened on any PC (irrespective of the processor architecture, compiler, etc). -
From the QDataStream doc:
"A data stream is a binary stream of encoded information which is 100% independent of the host computer's operating system, CPU or byte order. For example, a data stream that is written by a PC under Windows can be read by a Sun SPARC running Solaris."So you should be fine with doubles, but what bothers me more is that you say you want a binary file and yet you use platform dependant text to separate fields (the newline character and "EOF" string?). AFAIK binary formats don't usually use any field separators or markers like that. They rather keep offsets and sizes in some sort of data chunks.
-
Hi Chris, regarding the newlines the code be modified so that QString is used:
@line = "\n";
*dataStream << line;@This can be replaced above instead of '\n' and "\n".
But I do not understand your objection to "EOF"?
I am using QString too write this.
Then what is the problem here? -
There is no problem per se. I just think for a binary format (which is often chosen for compactness) it's a little wasteful.
Why do you need \n at all? QDataStream encodes the length of the string and knows sizes of different types. You can write consecutive fields without separating them with anything. If you really need there something then \n is a bad choice since QDataStream will treat it as a usual QString, add a type id, length etc. There's also matter of \n being different on linux/windows.
Similarly, what is the use of "EOF" sting at the end? Can't the stream just end? -
OK, removed all the \n and EOF stuff!
Thanks for your advice :)