C++ 在 Qt 中逐行读取文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5444959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:10:55  来源:igfitidea点击:

Read a text file line by line in Qt

c++qt

提问by Wassim AZIRAR

How can I read a text file line by line in Qt?

如何在 Qt 中逐行读取文本文件?

I'm looking for the Qt equivalent to:

我正在寻找相当于:

std::ifstream infile;
std::string line;
while (std::getline(infile, line))
{
   ...
}

回答by Sergio

Use this code:

使用此代码:

QFile inputFile(fileName);
if (inputFile.open(QIODevice::ReadOnly))
{
   QTextStream in(&inputFile);
   while (!in.atEnd())
   {
      QString line = in.readLine();
      ...
   }
   inputFile.close();
}

回答by LNJ

QFile inputFile(QString("/path/to/file"));
inputFile.open(QIODevice::ReadOnly);
if (!inputFile.isOpen())
    return;

QTextStream stream(&inputFile);
QString line = stream.readLine();
while (!line.isNull()) {
    /* process information */

    line = stream.readLine();
};

回答by R1tschY

Since Qt 5.5 you can use QTextStream::readLineInto. It behaves similar to std::getlineand is maybe faster as QTextStream::readLine, because it reuses the string:

从 Qt 5.5 开始,您可以使用QTextStream::readLineInto. 它的行为类似于std::getline并且可能更快QTextStream::readLine,因为它重用了字符串:

QIODevice* device;
QTextStream in(&device);

QString line;
while (in.readLineInto(&line)) {
  // ...
}

回答by adhityarizi

Here's the example from my code. So I will read a text from 1st line to 3rd line using readLine() and then store to array variable and print into textfield using for-loop :

这是我的代码中的示例。所以我将使用 readLine() 从第一行到第三行读取文本,然后存储到数组变量并使用 for-loop 打印到文本字段:

QFile file("file.txt");

    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QTextStream in(&file);
    QString line[3] = in.readLine();
    for(int i=0; i<3; i++)
    {
        ui->textEdit->append(line[i]);
    }