我有一个程序,我基本上从Qt网站偷走了试图打开文件.该程序拒绝打开任何我为什么感到困惑的事情.我找了很多文档,但发现没有什么可以解释为什么它不起作用.
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QTextStream>
#include <QString>
MainWindow::MainWindow(QWidget *parent) :
QWidget(parent)
{
QFile file("C:/n.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream in(&file);
QString f=in.readLine();
lab =new QLabel("error",this);
lab->setGeometry(100,100,100,100);
lab->setText(f);
}
Run Code Online (Sandbox Code Playgroud)
小智 6
在打开文件之前,您始终可以检查存在:
QFile file("myfile.txt");
if (!file.exists()) {
// react
}
Run Code Online (Sandbox Code Playgroud)
如果文件存在但未打开,则可以获取错误状态和消息:
QString errMsg;
QFileDevice::FileError err = QFileDevice::NoError;
if (!file.open(QIODevice::ReadOnly)) {
errMsg = file.errorString();
err = file.error();
}
Run Code Online (Sandbox Code Playgroud)
并始终:如果文件是开放的,那么记得关闭它.在你的例子中你没有:
file.close();
Run Code Online (Sandbox Code Playgroud)