Search code examples
c++qtqfile

How to reuse QFile?


I would like to save two files to a dir using the following code:

QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"),QDesktopServices::storageLocation(QDesktopServices::DesktopLocation),
                                         QFileDialog::ShowDirsOnly
                                         | QFileDialog::DontResolveSymlinks);
QFile file(dir.append("/GlobalMessage.txt"));
if(file.open(QIODevice::WriteOnly | QIODevice::Text)){
    QTextStream out(&file);

    for (int i=0;i<t_global.size();i++){
        out << t_global[i]<<" "<<y_lat.y[i]<<" "<<y_lng.y[i]<<" "<<y_alt.y[i]<<" "<<y_vx.y[i]<<" "<<y_vy.y[i]<<" "<<y_vz.y[i]<<"\n";
    }
}
// optional, as QFile destructor will already do it:
file.close(); 

file.setFileName(dir.append("/AttitudeMessage.txt"));
if(file.open(QIODevice::WriteOnly | QIODevice::Text)){
    QTextStream out(&file);

    for (int i=0;i<t_attitude.size();i++){
        out << t_attitude[i]<<" "<<y_roll.y[i]<<" "<<y_pitch.y[i]<<" "<<y_yaw.y[i]<<"\n";
    }
}
file.close();

However the seconde file.open() always fail.What is the proper way to reuse this file object?


Solution

  • append changes the underlying QString.

    This is the output of file.filename() in your program:

    "/tmp/GlobalMessage.txt"
    "/tmp/GlobalMessage.txt/AttitudeMessage.txt"
    

    Just use

    QFile file(dir + "/GlobalMessage.txt");
    

    and

    file.setFileName(dir + "/AttitudeMessage.txt");