Qt World Summit: Register Today!

Safe solution to serialize data

  • I want to serialize a bunch of data by QDataStream and read them after, my question is, how could I make sure the file only updated if all of the data has been written?

    QFile file("proxy_settings.dat");
        QMessageBox::warning(nullptr, tr("Error"), tr("Cannot write proxy data into file, your settings "
                                                      "of the proxies cannot be saved"));
    QDataStream stream(&file);
    for(int i = 0; i != ui->tableWidgetPoxyTable->rowCount(); ++i){
        //do something and dump data into file

    This naive solution work if everything going right, but it will generate corrupt file if the program exit before the data are written. Do I have an easy way to make sure all of the data can be written? Thanks

  • Lifetime Qt Champion

    @tham What you can do: first write to a temporary file. If you finish successfully then move (don't copy) this temporary file to its correct location (overwrite the old one). If your app crashes, then the old file will be still untouched. The temporary file should be on the same partition (in the same file system), then moving it is very fast as the file system does not need to copy its content.
    It can look like this during writing:


    After writing delete original_file.dat and move (or rename if both files are in the same directory) temp_file.dat to original_file.dat.

  • This is exactly what QSaveFile is for http://doc.qt.io/qt-5/qsavefile.html

Log in to reply