0

我使用 QTextStreamer 读取 QFile 使用

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

但在我的要求中,我只需要从我的文件中读取特定的行集。例如:如果文件包含 1034 行。用户只能从第 107 行到第 300 行中选择要读取并显示在文本框中。

如何调整 qtextStream 阅读器的位置以指向文件的特定行。

现在我实施为

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

line = stream.readLine();
4

1 回答 1

2

QTextStream 是一个流,而不是数组。那是因为您不阅读就无法获得某些内容。

某种方式是(只是一个最简单的例子):

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++;
    }

更难的方法:

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++;
    }
}
于 2016-05-24T06:07:36.600 回答