Solved 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 fileSomeone 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:
-
Read whole file into memory array/list, insert line, write whole array/list back to file.
-
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