C++ 将有效QFile转换为QString-QString为空
因此,我尝试通过执行以下操作将QFile转换为QString:C++ 将有效QFile转换为QString-QString为空,c++,string,qt,file,c++11,C++,String,Qt,File,C++11,因此,我尝试通过执行以下操作将QFile转换为QString: void MainWindow::openTemplateFile(QString location) { if (location.isEmpty()) return; else { QString variable; templateFile.setFileName(location); if (!templateFile.open(QFil
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();
}
}
}
templateFile确实存在,并且是MainWindow类的一部分。这也是简化的代码-在实际的程序中,我从文件中读取字符,它工作正常。位置字符串是QFileDialog::getOpenFileName函数的结果,我使用该函数打开一个txt文件。您可以调用
readAll()
两次。第二次,流位于文件的末尾,因此readAll()
没有要读取的内容,并返回一个空字符串。在调试输出中打印fileText
。两条注释:(1)readAll()
方法无法报告错误,(2)该方法返回QByteArray
(不是QString
),并且QString
构造函数将在数组中的第一个“0”处停止。如果有“0”字节,字符串将更短。@bnaecker那么如何有效地将QFile的内容读取到QString?@bnaecker OP调用QTextStream::readAll()
,而不是QFile::readAll()
。前者也会返回QString
是的,我理解。这只是一些混乱的调试
48 ""