c++ - 无法使用 QStandardPaths 打开文件

标签 c++ qt file io

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

对话框.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();
}

最佳答案

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

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

并且您只能在此之后创建一个文件。

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

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

关于c++ - 无法使用 QStandardPaths 打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31436967/

相关文章:

java - ObjectOutputStream/ObjectInputStream的文件操作问题

java - 如何让线程等待文件创建?

c++ - 创建字符宽度不可知函数

c++ - 转换 DirectX 接口(interface)

c++ - 如何在后台运行 QProcess?

c++ - Qt C++ - 删除 QTableWidget 中的行

c++ - 难以在C++中读取文件

C++ 列表从位置删除元素并将其放在末尾

c++ - *this 与 C++ 中的 this

c++ - Qt 链接器错误窗口