PDA

View Full Version : How do I correctly use QTextStream to read individual lines?



Sirox
10th October 2014, 03:52
Having a bit of trouble here, and can't find relevant functions to do what I need. I have a text file, a big list of words, with nothing separating them except each being on its own line. I want to read a line, do something with it, and then grab the next line, and basically repeat this until the end of the file is reached. I'm sure this is simpler than I am making it out to be but I am not very familiar with file-read functions


void Read(QString Filename)
{
QFile mFile(Filename);
if(!mFile.open(QFile::ReadOnly | QFile::Text))
{
return;

qDebug() << "could not open file for reading";
}

QTextStream in(&mFile);
QString mText = in.readLine();
//Do something with string
qDebug() << mText;
mFile.flush();
mFile.close();

}



So this little function (thanks to VoidRealms) can read the very first line of my file. I am not sure how to delete that line from the text stream and then read the next one.

Would it be better to do a readAll() into a string, and then work from that string? I intend for this particular data to be opened once when the file is executed, and then be called upon when needed, until the program is finished.

wysota
10th October 2014, 07:07
You do not "delete the line from text stream" as it is a stream - once you read it, it is "gone". In your case you just need to repeat the whole reading line process until you run out of lines. QTextStream docs even contain an example of doing that, there is no need to look for help on external sites, just read your docs.