How to write without overwrite in QFile

  • Hi
    My file "myfile.txt" contain the word "world" and i want to insert at beginning of my file "Hello " so that at the end my file contain exactly "Hello world"

    Here is my code

    QFile infile("myfile.txt");

        QTextStream t(&infile);;
        t<<"Hello ";

    But the problem is that this code overwrite in "myfile.txt" and "myfile.txt" contain at end "Hello ".
    How can i solve it?


  • I don't think there is a way to prepend data in a file. You can add "world" to a file containing "Hello " but not the other way around. You'll have to create a new file, dump what you want and then append what is contained in your original file.

  • Well I would not create a new file. You can create a buffer in memory, write "Hello " in the buffer, stream the file in your buffer and write it back to disk.
    But for very large files you need a second file cause your memory consumption would grow too high.
    Besides this it is not a good approach. Prepending/Inserting data in a file is very time consuming and inefficient. Appending the data at the end of a file is much faster.


  • Hi, That is not strange, but perfect valid as to file storage related issue. Think about it, what will happen with other data on the disk if you just prepend data to a file and the end of the file is shifted backwards. How is your program able to detect other files behind the file you're prepending??? It can't. The OS must do that, but won't. As said before, create a second 'store' file and use two file opens to open up the files. Use the streams to swap data from the first to the second file and prepend/append data where needed.
    If the files are extreme in size, you might want to consider multithreading or the QThreadpool.

  • @AlexRoot Can you show me the code if possible ?

  • Here is the code:

        QFile file("testfile");
        if( | QIODevice::Text))
            QByteArray buf("Hello ");
            buf += file.readAll();
            qDebug() << "error reading file";

    BUT it's not truncating the old content so the new content have to be bigger than the old one. If your second content could be smaller, just take the approach with a second file...
    Why don't you just append it to the end of the file?


Log in to reply