Search and edit text file for string



  • I am new to Qt and this is my first application.

    I need to search for a string in a text file and write another text file with the line that includes the search string and everything following it. I wrote the following code, but the search doesn't seem to be working. The new text file is blank because a match is not found. I would like to know what's wrong with the search.
    @
    int counter = 0;
    int linenumb = 0;
    QString search = " search string";
    QFile tempfile("C:\test\temp.textf");
    QFile workingdoc("C:\test\workingdoc.txt");
    tempfile.open(QIODevice::ReadOnly|QIODevice::Text);
    workingdoc.open(QIODevice::WriteOnly|QIODevice::Text);
    QTextStream in(&tempfile);
    QTextStream out(&workingdoc);
    while(!in.atEnd())
    {
    linenumb++;
    QString line = in.readLine();
    if (line == search)
    {break;}
    }

    while(!in.atEnd())
    {
    counter ++;
    QString line = in.readLine();
    if (counter >= linenumb)
    {out<<line<<endl;}
    }

    tempfile.close();
    workingdoc.close();
    

    }
    @
    [andreyc EDIT]: please use @ around code



  • Welcome to DevNet

    Let say in a file C:\test\temp.textf you have
    @
    line1
    line2
    line3
    @

    and search string is "line2"

    What do you expect as a result? Is it like this:
    @
    line2
    line1
    line2
    line3
    @

    If so then, you did not restart input stream between two loops, so your second loop continues to a read a file from the place where first one stopped.
    And I don't see where you write your "search string" to a file.



  • thanks andreyc.

    that's what I would like to write. I would like the new file to contain

    line 2
    line 3



  • Then you don't need counters.
    Just read from one file until you hit the search line and start to write after that. Something like this
    @
    QString line;
    while(!in.atEnd())
    {
    line = in.readLine();
    if (line == search)
    {
    found = true;
    out<<line<<endl;
    break;
    }
    }

    while(found && !in.atEnd())
    {
    line = in.readLine();
    out<<line<<endl;
    }
    @



  • thanks for your help andreyc.

    I fixed it, turns out it was the greater than or equal to operator. if you change the >= to <= in line 24 of my post, it works. :)


Log in to reply
 

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