qtqfileqtextstream

seek line in qtextStream


im using QTextStreamer to read a QFile using

if(file.open(QIODevice::ReadOnly | QIODevice::Text))
{
    QTextStream stream(&file);
    line = stream.readLine();
    //...

but in my requirement i need only to read particular set of lines only from my file. ex: if the file contains 1034 lines. user can select only from line 107 to 300 line to be read and display in a textBox.

how can i adjust the position of the qtextStream reader to point on the particular line of the file.

right now im implementing as

int count = 4;
while(count > 0)
{
    line = stream.readLine();
    count--;
}

line = stream.readLine();

Solution

  • QTextStream is a stream, not array. That because you can't get some line without read it.

    Some way is (just a simplest example):

    QFile file("file_name");
    QTextStream stream(&file);
    QStringList list;
    int line = 0;
    if(file.open(QIODevice::ReadOnly))
        while(!stream.atEnd()) {
            if(line == 4 || line == 5 || line == 6)
                list << stream.readLine();
            else
                stream.readLine();
            line++;
        }
    

    The harder way:

    if(file.open(QIODevice::ReadOnly)) {
        QByteArray ar = file.readAll();
        QByteArray str;
        for(int i = 0; i < ar.size(); i++) {
            if(line == 4 || line == 5 || line == 6) {
                if(ar.at(i) == '\n') {
                    list << QString::fromUtf8(str.replace("\r", ""));
                    str.clear();
                }
                else
                    str += ar.at(i);
            }
            if(ar.at(i) == '\n')
                line++;
        }
    }