QFile read/write
-
Hi Guys,
I'm using QFile to create .bat files for mapping network drive/printers. This is going to be used for a support department so i want to try and make it as free from user error as possible.
My Program reads in a bat file and displays the content of the file in a TextEdit window. There is a problem, if the bat file doesn't exist my program creates one, this is a default of QFile i think. How can i make it not create one? and do a test to confirm this?
@
QFile bat(finalpath); //finalpath is a QString containing the file path and name that i want to open to read
ui->batEdit->clear(); //batEdit is a textEdit object
bat.open(QIODevice::ReadOnly);
if(bat.open(QIODevice::ReadOnly))
{
QLabel* error = new QLabel("Cant Open file");
error->show();
}
QTextStream batStream (&bat);
QString line;
while(!batStream.atEnd())
{
line = batStream.readLine();
ui->batEdit->append(line);
}
bat.close();
@Secondly,
After reading the file, i then want to either create the file(if it doesn't exist) or append the file. There is a catch though, if one of the support engineers has misspelled the username, the folder structure then wouldnt exist. I dont want to create the folder structure with the QFile class, but i do want to create the file, if it doesn't exist. Is that at all possible? Am i living in an idealistic world...
my code so far, below;
@
bat.open(QIODevice::ReadWrite | QIODevice::Append);
QString letter = ui->letterEdit->text();
QString share = ui->ShareEdit->text();
QString command = "net use ";
command = command+letter+" \\isi-itn\"+share;
QTextStream fout(&bat);
fout << endl;
fout << command;
bat.close();
@Oh, and in case you're wondering at the code.. I'm a newbie. To C++(sort of) and Qt.
Thanks in advance
Michael
-
Check if the file exists first using "QFileInfo::exists()":http://doc.qt.nokia.com/latest/qfileinfo.html#exists.
-
open with QIODevice::ReadOnly does not create a file. The reason for the failure is that you reversed the logic. open returns true, in case it succeeded and returns fals in case it failed.
The following snippet prints "open FAILED" if the file does not exist:
@
QFile f("/tmp/qdn-test.bat");
if(f.open(QIODevice::ReadOnly))
qDebug() << "open ok";
else
qDebug() << "open FAILED";
@A better approach would be QFileInfo::exists(), as ZapB suggested.
And also make sure to abort the process in case the file does not exist. In your snippet, you just show the error message but continue in your workflow.
As a side note:
Don't use a QLabel and show for your error message. Have a look at [[Doc:QMessageBox]], especially at the static convenience methods to show a nice error box. -
[quote author="Volker" date="1312841948"]
As a side note:
Don't use a QLabel and show for your error message. Have a look at [[Doc:QMessageBox]], especially at the static convenience methods to show a nice error box.
[/quote]
Or [[Doc:QErrorMessage]], while we're at it :-)