0

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();
Noam M
  • 3,156
  • 5
  • 26
  • 41
Wagmare
  • 1,354
  • 1
  • 24
  • 58

1 Answers1

2

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++;
    }
}
Shtol Krakov
  • 1,260
  • 9
  • 20
  • thanks .im following in same way . but is it not possible to read from particular line of QFile. not only with textSream but also any other way is availabel ? Ex: in qtextDocument we can read at particular line using startWithLine( – Wagmare May 24 '16 at 06:16
  • 1
    @Wagmare To find the line number you have to count the number of line breaks, and to do that, there's no way around reading the file (unless you have a constant line length). QTextDocument might do that under the hood, but it doesn't make much of a difference if Qt is doing it or you are, it's just a few lines of code after all. – Karsten Koop May 24 '16 at 06:59