Search code examples
c++qtqfile

QFile: Avoid overwriting new data for existing files


Is it possible to do the following?

    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
    }

Solution

  • Try this.

    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() returns bool, so don't forget to check is file was opened correctly.

    From documentation:

    QIODevice::Append - The device is opened in append mode, so that all data is written to the end of the file.

    More information: http://qt-project.org/doc/qt-4.8/qiodevice.html#OpenModeFlag-enum