【问题标题】:Converting valid QFile to QString - QString is empty将有效的 QFile 转换为 QString - QString 为空
【发布时间】:2017-11-07 00:33:47
【问题描述】:

所以我试图通过执行以下操作将 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 文件。

【问题讨论】:

  • 两个cmets:(1)readAll()方法没有办法报错,(2)方法返回一个QByteArray(不是QString),那个QString构造函数将在数组中的第一个“0”处停止。如果有字节为“0”,则字符串会更短。
  • @bnaecker 那么如何有效地将 QFile 的内容读取到 QString 中?
  • @bnaecker OP 调用 QTextStream::readAll(),而不是 QFile::readAll()。前者也返回QString

标签: c++ string qt file c++11


【解决方案1】:

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

【讨论】:

  • 是的,我明白了。这只是一些混乱的调试
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-30
  • 2019-12-23
  • 2011-08-21
  • 2012-04-01
相关资源
最近更新 更多