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?
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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With