Search code examples
qtqstring

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?


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