QFile不会打开文件 [英] QFile won't open the file

查看:1231
本文介绍了QFile不会打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,我基本上从Qt网站偷了,试图获取一个文件打开。程序拒绝打开任何我困惑为什么。我已经查找了很多文档,但发现没有什么可以解释为什么它不工作。

I have a program that I basically stole from the Qt website to try to get a file to open. The program refuses to open anything I am confused as to why. I have looked for lots of documentation but found nothing can you please explain why it does not work.

#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);

}


推荐答案

该文件,你可以随时检查existense:

Before opening the file, you can always check the existense:

QFile file("myfile.txt");
if (!file.exists()) {
    // react
}

如果文件存在但没有打开,您可以得到错误状态和消息:

If file exists but does not open, you can get the error state and message:

QString errMsg;
QFileDevice::FileError err = QFileDevice::NoError;
if (!file.open(QIODevice::ReadOnly)) {
    errMsg = file.errorString();
    err = file.error();
}

并且始终:如果文件是openend,那么请记住关闭它。在您的示例中,您没有:

And always: if the file was openend, then remember to close it. In your example you didn't:

file.close();

这篇关于QFile不会打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆