[SOLVED]Trying to write a file using QFile after a button click
-
Hello All, I'm very new to Qt and haven't used C++ in quite a while. I am trying to use QFile to create a file when a button is clicked. I started by writing a read and write function and tested functionality in a Qt console application. The code worked and the file was created in my debug directory. When I try incorporating the code into a gui application, it seems as though the file is being written, then read but after the program closes there is no file in the debug directory. I'm sure I've done something incorrectly, any help or guidance would be greatly appreciated. My code is as follows:
@#include "dialog.h"
#include "ui_dialog.h"
#include <QFile>
#include <QTextStream>
#include <QDebug>void Write (QString Filename)
{
QFile mFile(Filename);
if(!mFile.open(QFile::WriteOnly | QFile::Text))
{
qDebug()<<"Could not open file";
return;
}
QTextStream out(&mFile);
out<<"doody";mFile.flush(); mFile.close();
}
void Read (QString Filename)
{
QFile mFile(Filename);
if(!mFile.open(QFile::ReadOnly | QFile::Text))
{
qDebug()<<"Could not open file for read";
return;
}
QTextStream in(&mFile);
QString mText = in.readAll();qDebug() << mText; mFile.close();
}
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
}Dialog::~Dialog()
{
delete ui;
}void Dialog::on_pushButton_clicked()
{
QString mFilename = "fudge.html";
Write(mFilename);
Read(mFilename);
}
@ -
I should have mentioned that I'm on a mac running 10.7.5. I used finder's search function the file is not found.
EDIT: I have the permissions set properly in the directory
-
I just compiled and ran the code in Windows 7, and it worked as I expected. This poses a problem, because my end product application needs to work on both windows and mac.
-
The files are contained in the application bundle, all I had to do was right click on the .app file and click show package contents.
-
Hi,
You should avoid writing files in an app bundle or just besides your application exec. It won't work everywhere. You should rather use one of the known read/write location that you can get from QDesktopServices/QStandardPaths depending on your Qt version
-
[quote author="SGaist" date="1384894992"]Hi,
You should avoid writing files in an app bundle or just besides your application exec. It won't work everywhere. You should rather use one of the known read/write location that you can get from QDesktopServices/QStandardPaths depending on your Qt version[/quote]
Thanks for the suggestion. I'm prototyping things right now, so I wasn't really thinking about where the file was going. In the end, there will probably be a hard coded filepath for the file to be written to specific to each machine that the program is used on.