PDA

View Full Version : QFile and Creating Files



Jingoism
28th July 2007, 09:12
Ok first off I am a total noob at C++ and QT as I just started a few days ago, but I have been trudging through some online tutorials and just recently hit a snag. I am quite sure it's a simple issue, but here goes.

Got a list widget, line edit widget and a button that when pressed outputs the text to the list widget and then outputs to a file. Now I got it working great as long as I hard coded the filename into my program, but when I wanted to possibly create a new file I could not figure out where to put it.

You can see below where I wanted to put it, but I knew it would not work since it was encapsulated by the if statement. I think my brain is fried from looking at all this for too long hehe.



void DialogImpl::doSomething() {
QString linedt = lineEdit->text(); // Set linedt to the text in the Line Edit box
if (!file.isOpen()) && ( linedt != "" ) { // If file is not open then open it
QFile file("/home/jingoism/" + linedt); // This is wrong, and the part I dont understand
QTextStream out(&file); // Also wrong, should go with QFile
file.open(QIODevice::WriteOnly | QIODevice::Text); // Open the file as Writeonly
listWidget->addItem("Opened File!"); // Verify in listWidget file is opened
listWidget->addItem(linedt); // Add the line of text to the listWidget
out << linedt << endl; // Add the line to the file
lineEdit->clear(); // Clear the LineEdit box
} else {
if ( linedt != "" ) { // If text in the Line Edit box is not null then proceed
out << linedt << endl;
listWidget->addItem(linedt);
lineEdit->clear();
}
}
}

marcel
28th July 2007, 09:40
Hey, is this compiling at all?
You got it all wrong and you are right with some things :).
You can do without QTextStream
QFile inherits QIODevice which has lower level methods for reading/writing files.

Your logic in writing this program is not correct.


void DialogIml::DialogImpl(...)
{
mFile = new QFile(somePath); //sice you require constatnt access to the file, it should be a member in your class.
mFile->open(QIODevice::WriteOnly); //this should create the file if it does not exist
//be careful because that could return false - if you lack permissions,etc
}

void DialogImpl::~DialogImpl()
{
if(mFile)
{
mFile->close();
delete mFile;
}
}

void DialogImpl::DoSomething()
{
QString linedt = lineEdit->text();
if(mFile->isOpen())
{
mFile->write(linedt.ascii());//Writes a QByteArray to the file.
}
}


Should be more or less like this.

Regards

Jingoism
28th July 2007, 17:11
Ahh thats exactly what I was looking for. I knew the answer was probably fairly simple, but I could not seem to grasp how I would obtain constant access to the file. Of course now it seems really simple and I feel like a tool... :D hehe.

Thank you for the quick response though as I am thoroughly enjoying QT.