【问题标题】:Can't open file using QStandardPaths无法使用 QStandardPaths 打开文件
【发布时间】:2015-07-15 17:19:16
【问题描述】:

我正在尝试创建一个在我按下按钮时打开文件的程序。我在头文件中创建了一个QStandardPath。然后我将 /myfile.txt 附加到它的末尾并尝试打开它。我刚开始使用 Qt,希望得到一些建议。

dialog.h:

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QStandardPaths>

namespace Ui {
class Dialog;
}

class Dialog : public QDialog
{
    Q_OBJECT

public:
    QString Location = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    explicit Dialog(QWidget *parent = 0);
    ~Dialog();

private slots:
    void on_btn_Read_clicked();

private:
    Ui::Dialog *ui;
};

#endif // DIALOG_H

对话框.cpp

#include "dialog.h"
#include "ui_dialog.h"
#include <QDebug>
#include <QStringList>
#include <QFile>

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::on_btn_Read_clicked()
{
    QFile myFile(Location.append("/myfile.txt"));

    if(!myFile.exists())
    {
        qDebug() << "File does not exist. attempting to create. . .";
        if (myFile.open(QIODevice::ReadWrite | QIODevice::Text)){
            qDebug() << "created :]";
        }
        else
        {
            qDebug() << "not created :[";
        }
    }
    myFile.close();
}

【问题讨论】:

  • qDebug() &lt;&lt; myFile.fileName();的结果真的存在吗?
  • 我不确定我是否理解?你想让我试试吗?我的代码中目前没有。
  • 是的,我试图告诉你,请检查调试窗口。在QFile 实例化之后写。然后检查显示的路径是否真的存在。
  • 这是我的调试:“C:/Users/MyName/AppData/Roaming/File_IO_Practice/myfile.txt”文件不存在。试图创造。 . .未创建:[
  • 你有写权限吗?尝试在那里创建一个文件。

标签: c++ qt file io


【解决方案1】:

您应该检查给定目录是否存在。如果没有,那么您需要创建完整路径,例如:

QDir().mkpath( /**/ );

而且你只能在此之后创建一个文件。

QFile file( filename );
if ( file.opne( /**/ ) )
{
    // ...
}

(但所有这些都是在你确定你有权限之后。)

【讨论】:

    猜你喜欢
    • 2019-01-06
    • 2010-12-17
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多