Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top