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");
    if(!file.open(QIODevice::WriteOnly)){
        QMessageBox::warning(nullptr, tr("Error"), tr("Cannot write proxy data into file, your settings "
                                                      "of the proxies cannot be saved"));
        return;
    }
    QDataStream stream(&file);
    for(int i = 0; i != ui->tableWidgetPoxyTable->rowCount(); ++i){
        //do something and dump data into file
        stream<<type<<host<<port<<user_name<<password;
    }
    

    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


  • Moderators

    @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:

    some_dir/
        original_file.dat
        temp_file.dat
    

    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
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.