[SOLVED] Reading multiple files with QFile

Issue

I want to read multiple files. I get en error in QFile because it reads only one file at once.

  • How can I solve this problem?
  • And how can I iterate my files and use them.
QStringList fileNames;
fileNames = QFileDialog::getOpenFileNames(this,
  tr("choose"),
  "up.sakla",
  tr("choosen(*.up)"));

if (fileNames.isEmpty())
  return;

QFile file(fileNames);
file.open(QIODevice::ReadOnly);
QDataStream in ( & file);
QString str;
qint32 a; in >> str >> a;

Solution

I understand that you have some files within a folder and you would like to read a list of files (the ones that you selected through the QFileDialog)

Here is the complete code:

#include <QApplication>
#include <QFileDialog>
#include <QDebug>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
   
    QStringList fileNames;



    fileNames = QFileDialog::getOpenFileNames(nullptr, "choose", "up.sakla", "choosen(*.up)");

    for (auto xfile : fileNames)
    {
        QFile file (xfile);
        file.open(QIODevice::ReadOnly);
        QTextStream in(&file);
        QString str;
        while (!in.atEnd())
        {
           //read all the file content as a text
           str = in.readAll();
           qDebug() << str;
        }


    }

    return app.exec();
}

If the contents of each file is the following:

  • file 1 content
File1 11
  • file 2 content
File1 12
  • file 3 content
File1 13

The output of the program would be as follows:

"File3 13\n \n"
"File1 11\n \n"
"File2 12\n \n"

Answered By – Pat. ANDRIA

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *