QFile:避免覆盖现有文件的新数据

时间:2014-10-09 17:37:27

标签: c++ qt qfile

是否可以执行以下操作?

    QFile file("Test.txt")
    If (file.exists) {
        //Start writing new data at the end of the file and DO NOT overwrite existing data
    } else {
        //Start from the beginning
    }

2 个答案:

答案 0 :(得分:4)

试试这个。

QFile file("Test.txt")
if (file.exists()) {
     if(file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
     {
          QTextStream out(&file);
          out << "new data";
     }
     else
         qDebug() << "file not open";
} else {
}

open()返回bool,所以不要忘记检查文件是否正确打开。

来自文档:

QIODevice::Append - 设备以追加模式打开,以便将所有数据写入文件末尾。

更多信息:http://qt-project.org/doc/qt-4.8/qiodevice.html#OpenModeFlag-enum

答案 1 :(得分:1)

是的,你可以这样做:

QFile file(filename);
file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text);
QTextStream out(&file);
out << "your text";
相关问题