[SOLVED] How can I override a text line in txt file.



  • @ QFile file3(_filename3);
    QTextStream out3(&file3);
    if(!file3.open(QFile::WriteOnly)){
    qDebug() << "could not open file for writing";
    return;
    }else{
    QString item1 = ui->lineEdit_4->text();
    QString item2 = ui->lineEdit_5->text();
    out3 << item1 << "\r\n" ;
    out3 << item2 << "\r\n";
    out3 << _directory3;
    file3.flush();
    file3.close();
    }
    @

    I get three directories that appear in my lineEdits and write them in a text file.
    When I change some directory on my LineEdit eg _directory3, it should be written in my text file to replace the old. Only what happens the following problem: If I select the directory that is mair than the old (more characters), when you print the text file, it not replaces the old completely. For example:
    Old: C :/ Users / eng / Desktop / lineEditqt.txt
    New: C :/ Users / eng / Desktop / qt.txt.
    in my text file it is written:
    C :/ Users / eng / Desktop / qt.txtitqt.txt
    and not as it should be, it would be like this:
    C :/ Users / eng / Desktop / qt.txt

    How can I solve it?


  • Lifetime Qt Champion

    Hi,

    One question first: is that the only content of your file ?



  • In my txt file has just 3 paths that I can override.



  • Hii

    your given code is working right if i remove line 11.
    i have doubt on line 11
    What is this _directory3 ?
    is this same as item1 or item2 ?
    if yes How are you getting _directory3 ?


  • Lifetime Qt Champion

    Then you should just read the file line by line in e.g. a QStringList. Replace the line you modified in the QStringList and then overwrite the content of the original file with the content of the QStringList.



  • Can you show me an example with this?


  • Lifetime Qt Champion

    Of reading a file line by line ?



  • No. I don't now how to use QStringList in this case.


  • Lifetime Qt Champion

    Then please, take some time to read the documentation of this class.
    One way:
    @QStringList lines
    //open file etc.
    while(!steam.atEnd()) {
    lines << stram.readLine();
    } @

    There are also other way to do that e.g. using QString::split



  • The solution was simpler than I imagined.
    Simply put:
    @if(!file3.open(QFile::ReadWrite | QFile::Truncate)){
    qDebug() << "could not open file for writing";
    return;@


  • Lifetime Qt Champion

    With that you don't just change one line like you ask for, you are overwriting everything.



  • Yes, but I also rewrite those who have not been changed.



  • if your problem is solved then make this title as SOLVED by adding [SOLVED] tag before the title.


Log in to reply
 

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