read a text file to QStringList

19,798

Solution 1

I assume that every line should be a separate string in the list. Use QTextStream::readLine() in a cycle and on each step append the returned value to the QStringList. Like this:

QStringList stringList;
QFile textFile;
//... (open the file for reading, etc.)
QTextStream textStream(&textFile);
while (true)
{
    QString line = textStream.readLine();
    if (line.isNull())
        break;
    else
        stringList.append(line);
}

Solution 2

    QFile TextFile;
    //Open file for reading
    QStringList SL;

    while(!TextFile.atEnd())
    SL.append(TextFile.readLine());

Solution 3

If the file isn't too big, read the whole content into a QString and then split() it into a QStringList.

I like using the QRegExp version to handle linefeed from different platforms:

QStringList sList = s.split(QRegExp("(\\r\\n)|(\\n\\r)|\\r|\\n"), QString::SkipEmptyParts);

Solution 4

I like my code to be fully indented/paranthesized with obvious variable names (they may take longer to type but are much easier to debug) so would do the following (but changing "myTextFile" and "myStringList" to more sensible names, such as "employeeListTextFile")

QFile myTextFile;
QStringList myStringList;

if (!myTextFile.open(QIODevice::ReadOnly))
{
    QMessageBox::information(0, "Error opening file", myTextFile.errorString());
}
else
{  
    while(!myTextFile.atEnd())
    {
        myStringList.append(myTextFile.readLine());
    }

    myTextFile.close();
}
Share:
19,798
defiant
Author by

defiant

Updated on October 14, 2022

Comments

  • defiant
    defiant over 1 year

    I have a text file. I need to read it to a QStringList. there are no line seperators. I mean each line in the text file is in a new line. So is there anyway i can do this?