C++ QFile 不会打开文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15619517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:33:27  来源:igfitidea点击:

QFile won't open the file

c++fileqtqfile

提问by Ville Lukka

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.

我有一个程序,我基本上是从 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);

}

回答by Ville Lukka

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

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

并且总是:如果文件是开放式的,那么记得关闭它。在您的示例中,您没有:

file.close();

回答by arun_vj

FileError QFile::error() const Returns the file error status. The I/O device status returns an error code. For example, if open() returns false, or a read/write operation returns -1, this function can be called to find out the reason why the operation failed. See also unsetError().

FileError QFile::error() const 返回文件错误状态。I/O 设备状态返回错误代码。例如,如果 open() 返回 false,或者读/写操作返回 -1,则可以调用此函数来查找操作失败的原因。另见 unsetError()。

Post the error code. Isn't it supposed to be QFile file("C:\n.txt"); \ not / in windows?

贴出错误代码。不应该是QFile file("C:\n.txt"); \ 不是 / 在 Windows 中?