Read a text file line by line in Qt

C++Qt

C++ Problem Overview


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

I'm looking for the Qt equivalent to:

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

C++ Solutions


Solution 1 - C++

Use this code:

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

Solution 2 - C++

This code might be a little simpler:

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

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

Solution 3 - C++

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

QIODevice* device;
QTextStream in(&device);

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

Solution 4 - C++

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 :

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]);
    }

Solution 5 - C++

Or something like this, for read from file:

The included lib:

#include "QFile"
#include "QDir"

The Code:

QFile file;
file.setFileName("text.txt");
QDir::setCurrent("C:/Users/USER_NAME/Documents/QTCreatorWorkspace/untitled1");
QTextStream data(&file);

if(file.open(QIODevice::ReadOnly)){
    ui->plainTextEdit->insertPlainText(file.readAll());
    file.close();
}
else{
    //Error statement
}

And for write to file: The Code:

QFile file;
file.setFileName("text.txt");
QDir::setCurrent("C:/Users/USER_NAME/Documents/QTCreatorWorkspace/untitled1");
QTextStream data(&file);

if(file.open(QIODevice::ReadWrite)){
    data << ui->plainTextEdit->toPlainText();
    file.close();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWassim AZIRARView Question on Stackoverflow
Solution 1 - C++SergioView Answer on Stackoverflow
Solution 2 - C++LNJView Answer on Stackoverflow
Solution 3 - C++R1tschYView Answer on Stackoverflow
Solution 4 - C++adhityariziView Answer on Stackoverflow
Solution 5 - C++RuprechtView Answer on Stackoverflow