Nominate our 2022 Qt Champions!

Inserting text at the beginning of a file in QFile

  • Is there any way to append some text to the front of a text file using QFile?
    adding QIODevice::Append flag will always appends to the end, i tried QFile::seek(0) also but did nothing
    any help please?
    (Licenses should be at the top of the source-code files)

  • After opening the file make sure it is not sequential (i.e. file.isSequential() ).

    You mentioned seek(0) didn't work. Maybe (I didn't try this) the value is an offset from where you are now which is the end of the file. If, for example, the file size is 1000 bytes maybe you need to use ?

    I use a shell script and parameters built around the 'sed' command for this. It looks for the old license data (at the top of the file) and updates it as needed. I don't know if something like this is an option but just throwing that out there.

  • Lifetime Qt Champion


    No, nor is it possible with standard C++. What you can do is create a new file, add your new content and then append the old one. Close both files and replace the original by the new.

    Hope it helps

Log in to reply