How to make a QString from a QTextStream?

烂漫一生 提交于 2020-01-02 02:47:07

问题


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.



来源:https://stackoverflow.com/questions/15824043/how-to-make-a-qstring-from-a-qtextstream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!