我想使用以下代码将两个文件保存到一个目录:

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();

但是 seconde file.open() 总是失败。重用这个文件对象的正确方法是什么?

最佳答案

append 更改底层 QString

这是程序中 file.filename() 的输出:

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

只需使用
QFile file(dir + "/GlobalMessage.txt");


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

关于c++ - 如何重用 QFile?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26938417/

10-12 07:10