How to make a QString from a QTextStream?

2019-04-24 12:01发布

问题:

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?

回答1:

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();


回答2:

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.



标签: qt qstring