Reading a text file in Qt

I want to read a huge text file in which I will divide the lines according to a comma (,) and store the lines in an array. So how to do it. Is there any class that performs an action like StringTokenizer, as in badaOS. I tried QFile but could not read the whole file.

+3
source share
5 answers

QTextStream allows you to read line by line

QFile file(hugeFile);
QStringList strings;
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
{
    QTextStream in(&file);
    while (!in.atEnd()) {
        strings += in.readLine().split(";"); 
    }
}
+10
source

You can use file streams.

QFile file = new QFile(hugeFile);      
file.open(QIODevice.OpenModeFlag.ReadOnly);       
QDataStream inputStream = new QDataStream(file);
QStringList array;
QString temp;

while(!inputStream.atEnd()) {
  inputStream >> temp;
  array << temp.split(";");
}

Please note that this is unverified (pseudo) code, hope this helps.

+1
source

:

QFile file( ... );
file.read(1000); // reads no more than 1000 bytes

:

file.readLine();

, .

0

, file.read(an_appro_number), file.atEnd() - false.

( File.read()), "(, QString ( )). ',', ( QString split(): X- ( 1000 1 ) , . ( file.atEnd()) . , . , file.atEnd():)

Or, as an alternative, you can read the file character by character and check the "" manually, but it is always better to read more than 1 character (this is more efficient if you read more).

0
source

It will not capture spaces after the decimal point. If this is unacceptable, feel free to optimize the regex. You can probably also reduce the number of inclusions at the top. I was just happy. I tested this in a file with a line of 1600, and it seems to have worked well with Qt 5.6

#include <QCoreApplication>
#include <QFile>
#include <QIODevice>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QRegularExpressionMatchIterator>
#include <QString>
#include <QStringList>
#include <QTextStream>

int main(int argc, char * argv[])
{
    QCoreApplication app(argc, argv);

    QFile file("C:\\PathToFile\\bigFile.fileExt");
    QStringList lines;
    QStringList matches;
    QString match;

    file.open(QIODevice::ReadOnly | QIODevice::Text);
    while(!file.atEnd())
    {
      lines << file.readLine();
    }
    file.close();

    QRegularExpression regex("(^|\\s|,)\\K\\w.*?(?=(,|$))");
    QRegularExpressionMatchIterator it;

    foreach (QString element, lines)
    {
        it = regex.globalMatch(element);

        while(it.hasNext())
        {
            QRegularExpressionMatch qre_match = it.next();
            match = qre_match.captured(0);
            matches << match;
        }
    }

    return 0;
}
0
source

Source: https://habr.com/ru/post/1790647/


All Articles