PDA

View Full Version : Populate QDataStream and only write to QIODevice under a certain condition



JPNaude
30th June 2010, 06:54
Hi

What would the best way be to do this:

I have a QDataStream which saves project data to a file. Currently I do it like this:



QFile file(file_name);
file.open(QIODevice::WriteOnly);
QDataStream stream(&file); // we will serialize the data into the file
// Now I stream lots of stuff to the stream.


However sometimes something goes wrong in the project saving and in that case I still need the original file. One way I can think of doing it is to write out a temp file and when successfull copy it over the current file. But I'm sure there must be a better way.

Can I create the stream and then flush it to the file all at once when everything went alright? Or what is the recommended way to do this.

Thanks,
Jaco

tbscope
30th June 2010, 07:25
Your definition of "something goes wrong" is flawed.

In your definition, you only take into account problems while constructing the datastream.
However, writing the datastream to a file can go wrong too.

In other words, even if your datastream is completely correct, writing it to a file can result in a corrupt file when, for example, there's not enough disk space or when there are conflicts in who has access to the file etc...

Therefor, your suggestion to work with temporary files is the best way to check if the saved file is correct.

You could use a version control system too of course, like svn etc...

JPNaude
30th June 2010, 10:48
Thanks! Good point