正在将有效的 QFile 转换为 QString - QString 为空

Converting valid QFile to QString - QString is empty

本文关键字:QString 为空 转换 QFile 有效      更新时间:2023-10-16

所以我正在尝试通过执行以下操作将QFile转换为QString:

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

但是,在调试控制台中我得到以下结果:

48 ""

templateFile 确实存在,并且是 MainWindow 类的一部分。这也是简化的代码 - 在实际程序中,我从文件中读取字符并且它工作正常。位置字符串是 QFileDialog::getOpenFileName 函数的结果,我用它来打开一个 txt 文件。

你给readAll()打了两次电话。第二次,流位于文件末尾,因此readAll()没有要读取的内容并返回一个空字符串。改为在调试输出中打印fileText