PDA

View Full Version : i can write to a file using QFile, but can not do it using QFile *, why?



htroyo
9th May 2011, 04:37
hello, i was creating a basic and create a private QFile * and QTextStream * in my class because i wanted to use them inside slots, but i realized that i was able to open, read and even create files but was not able to write to them, after some tests i decided to use a QFile inside every slot (read the file and write contents into a QTextEdit when a button is pressed, save the file when other button is clicked, etc) that is just used inside the function and then deleted, and i were able to write to files using the QFile, but not the QFile *, i will contine using QFile but i want to know why i cant write to files using a QFile *, thanks

rsilva
9th May 2011, 04:49
If you use QFile*, you're declaring a pointer, you need to use "new QFile()" to it works.
And open it with the option for writing ^^

htroyo
9th May 2011, 05:15
yes, i know it is a pointer, i used f->open(QFile:;WriteOnly) to open the file and declared the text stream to write, but it doesnt work, i have to use a QFile instead of QFile * because it doesnt write content

Added after 4 minutes:

... and file->error() returns QFile:;NoError

ChrisW67
9th May 2011, 06:49
Works fine:


#include <QtCore>
#include <QDebug>

int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);


QFile *outFile = new QFile("out.txt");
if (outFile->open(QIODevice::WriteOnly)) {
outFile->write("See, it does get out!\n");
outFile->close();
}
delete outFile;

QFile *inFile = new QFile("out.txt");
if (inFile->open(QIODevice::ReadOnly)) {
QByteArray line = inFile->readLine();
inFile->close();
qDebug() << line;
}
delete inFile;

return 0;
}

gives


"See, it does get out!
"


So, the question becomes what are you doing wrong? Are you attempting to write a file somewhere you do not have permission (e.g. under Program Files on Windows)? Are you not writing or reading the file you think you are?

high_flyer
9th May 2011, 10:52
yes, i know it is a pointer, i used f->open(QFile:;WriteOnly) to open the file and declared the text stream to write,

... and file->error() returns QFile:;NoError
It looks like you didn't initialize the pointer as rsilva noted:

you need to use "new QFile()" to it works.