Evan B
Evan B

Reputation: 83

Can't open file using QStandardPaths

I am trying to create a program that opens a file when I push a button. I have created a QStandardPath in the header file. I then append /myfile.txt to the end of it and try to open it. I am just starting out with Qt and would like some advice.

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

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

Upvotes: 3

Views: 1137

Answers (1)

p.i.g.
p.i.g.

Reputation: 2995

You should check if the given directory is exist. If not then you need to create the full path with for example:

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

And you can create a file only after this.

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

(But all of these things are only after you are sure that you have permission.)

Upvotes: 3

Related Questions