Save file with default extension
-
Hello to everyone:
First of all thanks a lot for reading this post and being able to help.
I would like to save a file with a default extension, so user has just to write the file name not extension. For example:
The file has to be a .txt .
User just write myfile
and file has to be myfile.txtMy code looks like:
QString outputFilename = QFileDialog::getSaveFileName(this, "Save TXT", "/home", "files TXT (*.txt)"); QFile outputFile(outputFilename); outputFile.open(QIODevice::WriteOnly); if(!outputFile.isOpen()) //If the user have choosen a file then: { //TODO mostrar ventana emergente de que no se puede abrir el archivo; } /* Point a QTextStream object at the file */ QTextStream outStream(&outputFile); /*Write Points*/ .......
But like this user has to put myfile.txt ....
Any waty to that what I want?
Thanks a lot!
-
QFileDialog::getSaveFileName provides only the input as done by the user. The filters are used only for filtering the files found for display in the dialog. It may give also a hint to the user what kind of extension of files are expected. However, the user may "overwrite" this advice and write anything.
IMHO it is the only logical way to handle the proper return of the routine. Otherwise how do you want to handle the case that the user does not want to have the suggested extension.
Therefore, in case the file is not available yet and it has to be created you can add the extension in your code. In order to avoid duplication of the same extension yopu can use QFileInfo::suffix()
-
@koahnig I agree that the filters are used to filter the files that are being displayed on the dialog. However, the
QFileDialog
is an operating system dependent implementation. At least in case of Windows I can ensure you that when you just type the file name without any extension (eg. MyFile) it will automatically append the extension of the currently selected filter (it results in MyFile.txt).
At least that's how it works for me on Windows 10.I have no idea how other operating systems handle this. Other people might be able to shed some light on this.
Of course the advice/recommendation from @koahnig is totally vaild: You can always check manually if a file extension has been added and add it programmatically if it's missing. -
You are right. I did not bother to try in windows 10 before. I have just tested it and it does always append ".txt" when it not there yet. It ends even in "file..txt" when the user types "file.".
It is even worse I had remembered, when writing:
QString fname = QFileDialog::getSaveFileName(0,"String", "C:/", "files (*);;another file txt (*.txt)" );
always ".txt" is appended. This is under win 10. I thought the behaviour was different before.
Also I do not remember how it should be in other OS, especially with the different linux distros.