9

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?

Fabio Cardoso
  • 1,181
  • 1
  • 14
  • 37
Dave
  • 477
  • 2
  • 5
  • 18
  • You don't open the file, look at my answer. – dtech Apr 05 '13 at 00:54
  • Thanks for the answers. I'm building a BB10 app and unfortunately I can't get this to work. I'm most sure it is something else I am doing so. But I can't choose an answer until I figure what else is wrong. – Dave Apr 05 '13 at 04:58
  • Well, it should work, it is simple and straightforward. Debug your code step by step and you will find your mistake. BB doesn't change QFile, so the problem is your implementation. – dtech Apr 05 '13 at 10:20

2 Answers2

19

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();
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
dtech
  • 47,916
  • 17
  • 112
  • 190
3

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.

Cutterpillow
  • 1,717
  • 13
  • 32
  • 1
    yes, you are right, it is pointless to resize considering the string considering there is no initial data to append to. gonna fix my answer as well... – dtech Apr 05 '13 at 01:24