Reading multiple files with QFile

Viewed 388

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;
2 Answers

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"

as you can see in th official do here

This is a convenience static function that will return one or more existing files selected by the user.

on the other hand QFile constructor is not accepting that QStringList(doc)

enter image description here

what you can do is loop over every element on the list

for(auto x : fileNames)
{
    QFile file(x);
    file.open(QIODevice::ReadOnly);
    QDataStream in(&file);   
    QString str;
    qint32 a;
    in >> str >> a;
}
Related