2

So I am trying to convert a QFile into a QString by doing the following:

void MainWindow::openTemplateFile(QString location)
{
    if (location.isEmpty())
        return;
    else
    {
        QString variable;
        templateFile.setFileName(location);
        if (!templateFile.open(QFile::ReadOnly | QFile::Text))
        {
            QMessageBox::information(this, "Unable to open template", 
            templateFile.errorString());
            return;
        }

        else    // file opened and ready to read from
        {
            QTextStream in(&templateFile);
            QString fileText = in.readAll();
            qDebug() << templateFile.size() << in.readAll();
        }
    }
}

However, in I get the following result in the debug console:

48 ""

templateFile does exist and is part of the MainWindow class. This is also simplified code - in the actual program I read chars from the file and it works correctly. The location string is a result of the QFileDialog::getOpenFileName function, which I open a txt file with.

3
  • Two comments: (1) the readAll() method has no way to report errors, and (2) the method returns a QByteArray (not a QString), and that QString constructor will stop at the first "0" in the array. If there are bytes of "0", the string will be shorter. Commented Nov 7, 2017 at 1:07
  • @bnaecker so how would you efficiently read a QFile’s contents to a QString? Commented Nov 7, 2017 at 1:10
  • @bnaecker The OP calls QTextStream::readAll(), not QFile::readAll(). The former does too return a QString Commented Nov 7, 2017 at 1:11

1 Answer 1

1

You call readAll() twice. The second time, the stream is positioned at end-of-file, and so readAll() has nothing to read and returns an empty string. Print fileText in your debug output instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I understand that. This was just some messy debugging

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.