How to reuse QFile?

1.4k views Asked by At

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?

2

There are 2 answers

0
Simon Warta On BEST ANSWER

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");
0
dtech On

It is probably an issue with the path you generate, because this code actually works for me:

QFile file("d:\\a.txt");
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
    qDebug() << file.readAll();

    file.close();

    file.setFileName("d:\\b.txt");
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << file.readAll();
    }
}

EDIT: Yup, Simon spotted it first, thou appends too much.