Important: Please read the Qt Code of Conduct -

add line x in the QFile (text file )

  • Hi guys,
    my problem is , i want to write (add) a QString in a file ( text file ) in line x without losing the other lines
    for exemple my text file contains 200 lines , i want to add "hello world" in line 150 (so the file will contains 201 lines )
    I tried with file.write() but it always add in the last position of the text file

    Someone can help me ? thanks

  • @Zunneh
    This question gets asked many times :)

    You cannot do this just by e.g. write, that will either append or overwrite depending on how you opened the file.

    You wish to insert a line in the middle, moving everything else "downward". You can only do this one of two ways:

    1. Read whole file into memory array/list, insert line, write whole array/list back to file.

    2. Open existing file for read line at a time, open new, distinct file for output line at a time, loop reading/writing, insert extra line into output at appropriate point. On successful conclusion, delete original file, rename new file to old file. Personally I like this way (no memory usage, no potential "partial overwrite" of file), though #1 is less code to write.

  • @JonB ok thank you

Log in to reply