QFile won't open the file

旧城冷巷雨未停 提交于 2020-01-04 02:02:07

问题


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

}

回答1:


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



回答2:


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().

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



来源:https://stackoverflow.com/questions/15619517/qfile-wont-open-the-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!