Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read a text file to QStringList

Tags:

file

qt

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?

like image 578
defiant Avatar asked Feb 23 '11 12:02

defiant


People also ask

How do I open and read a file in Qt?

The file is opened with open(), closed with close(), and flushed with flush(). Data is usually read and written using QDataStream or QTextStream, but you can also call the QIODevice-inherited functions read(), readLine(), readAll(), write().

How do you edit a text file in Qt?

The QTableWidget ui has four push buttons(ADD,EDIT,DELETE,CLOSE). On clicking ADD/EDIT other ui opens up which Add's and Edit's the data on a push button SAVE. Clicking SAVE will add new entry IF ADD is clicked in text file while clicking SAVE will edit updated values if Edit is clicked.


2 Answers

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);
}
like image 142
Daggerstab Avatar answered Oct 17 '22 14:10

Daggerstab


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

    while(!TextFile.atEnd())
    SL.append(TextFile.readLine());
like image 31
Alex Avatar answered Oct 17 '22 14:10

Alex