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
- QTextStream batStream (&bat);
- QString line;
- line = batStream.readLine();
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;
Oh, and in case you’re wondering at the code.. I’m a newbie. To C++(sort of) and Qt.
Thanks in advance
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:
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 QMessageBox, especially at the static convenience methods to show a nice error box.