Search code examples
c++qtfileqlistwidget

C++ Qt - Reading specific portion of a text file


I want to read a specific portion of a text file in a list widget. I have try different ways and looked online for some solutions but I couldn't find much. Im new using Qt but getting along well with it for the most part.

QFile YearInfo("C:/Users/Documents/info.txt");
        YearInfo.open(QIODevice::ReadWrite | QIODevice::Text);
        if(YearInfo.isOpen()){
            QTextStream in(&YearInfo);
            bool readEnabled = false;
            QString outputText, startToken = line, endToken = "*"; // line = "2019"
            while(!in.atEnd()){
               QString getLine = in.readLine();
               if(getLine == endToken){
                   readEnabled = false;
               }

               if(readEnabled){
                   outputText.append(getLine + "\n");
               }

               if(getLine == startToken){
                   readEnabled = true;
               }
            }
            ui->listWidget->addItem(outputText);
        }
            YearInfo.flush();
            YearInfo.close();

Text File contains:

2019 Position Division Title Date (W.M./R.M./J.R) *

2020 Position Division Title Date (P.M./V.R/S.T) *


Solution

  • The code that you have written works as long as you are trying to extract a section of text formatted in the following way

    2019
    Position Division Title   <~~ this line is extracted
    Date (W.M./R.M./J.R)      <~~ this line is extracted
    More stuff                <~~ this line is extracted
    *
    

    If you have something formatted in the following way

    2019 Position Division
    Title Date (W.M./R.M./J.R) *
    
    2019 Position Division Title Date (W.M./R.M./J.R) *
    

    nothing will be extracted because you start the extraction when you find a line that contains only the startToken. Same thing for the end token.

    You could try to modify the while loop in your code in the following way

    while(!in.atEnd()){
        QString getLine = in.readLine().trimmed();
    
        if(getLine.startsWith(startToken)){
            readEnabled = true;
        }
    
        if(readEnabled){
            outputText.append(getLine + "\n");
        }
    
        if(getLine.endsWith(endToken)){
            readEnabled = false;
        }
    }
    

    Now you are checking if the line startsWith the startToken. Here I also added a trimmed instruction to remove white spaces at the beginning and at the end of each line (just in case...). The same thing is done with endsWith for the endToken.

    Also it would be best to open the device in read-only mode, since you are not modifying it anyway

    YearInfo.open(QIODevice::ReadOnly | QIODevice::Text);
    

    and also the flush at the end is redundant.

    Hope this helps =)