Dave
Dave

Reputation: 477

How to make a QString from a QTextStream?

Will this work?

QString bozo;
QFile filevar("sometextfile.txt");

QTextStream in(&filevar);

while(!in.atEnd()) {
QString line = in.readLine();    
bozo = bozo +  line;  

}

filevar.close();

Will bozo be the entirety of sometextfile.txt?

Upvotes: 9

Views: 15370

Answers (2)

dtech
dtech

Reputation: 49309

Why even read line by line? You could optimize it a little more and reduce unnecessary re-allocations of the string as you add lines to it:

QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return;
QTextStream in(&file);
QString text;    
text = in.readAll();
file.close();

Upvotes: 19

Cutterpillow
Cutterpillow

Reputation: 1777

As ddriver mentions, you should first open the file using file.open(…); Other than that, yes bozo will contain the entirety of the file using the code you have.

One thing to note in ddriver's code is that text.reserve(file.size()); is unnecessary because on the following line:

text = in.readAll();

This will replace text with a new string so the call to text.reserve(file.size()); would have just done unused work.

Upvotes: 3

Related Questions