PDA

View Full Version : Adding default extension to the file



rookee
17th November 2015, 19:47
Hi,

I'm trying to save the files with a default extension. With the following code snippet, the file does save with the specified file name but it doesn't attach the extension to it. Can someone please help me. Thanks in advance.


QString fileName = QFileDialog::getSaveFileName(this, tr("Save Logs"),"/Tmp/",tr("*.csv"));
if(!fileName.isEmpty())
{
QFile f(fileName);
if(!fileName.endsWith(".csv"))
fileName = fileName + ".csv";
f.open(QIODevice::WriteOnly);

anda_skoa
17th November 2015, 20:04
You are modifying fileName after you've used it to initialize "f".

Cheers,
_

rookee
17th November 2015, 21:32
Could you please elaborate. How do I use fileName instead of f and check if the user entered extension, if the extension is not entered attach the extension and save it.

d_stranz
18th November 2015, 00:52
if ( !fileName.isEmpty() )
{
if ( !fileName.endsWith(".csv") )
fileName += ".csv";

QFile f( fileName );
f.open( QIODevice::WriteOnly);

// ...
}

anda_skoa
18th November 2015, 08:13
Could you please elaborate.

C++ is an imperative language.
Each statement potentially changes the state of the machine.
Statements are executed in order of sequence in the code.

so


QFile f(fileName);
fileName = ...;

first executes the creation of "f", then the modification of fileName.



How do I use fileName instead of f and check if the user entered extension

You currently don't use f to check for the extension so that questions does not make any sense.



if the extension is not entered attach the extension and save it.
You do that already.

Cheers,
_

rookee
18th November 2015, 21:49
Thanks a lot d_stranz and anda_skoa. I really appreciate it.