How to replace line 's partial text of a text file



  • I get to deal with a text file,read it line by line.

     @ QFile file(fileName);
    

    if (!file.open(QIODevice::ReadWrite))
    return;
    QTextStream in(&file);
    while (!in.atEnd()) {
    QString line = in.readLine();
    process_line(line);
    //------------------ after do some replace of line's part text, I want to write the new line text back. any advice??
    }@
    PS: I don't want to write a new file to replace the old one. I just want to modify the original.

    thanks in advance.



  • Hi,
    Very simple, make a temporary copy file and add the data you need added to it. Then remove the old file, rename the new file and your done!
    There are no possibilities to alter text in the middle of a file! How could you, think about it, the data is stored on a drive. The OS determines where, but there is no guarantee that data added to the file will fit on that exact location. Maybe there is an other file placed just after your file. Add a byte and then what? Place the last by somewhere else?? Nup, not possible. Make a deep copy to a temp file, add data and rename.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.