4

I have a piece of code to download a file from server. However, due to server constraint, I can not put .exe file at server. So I rename my XXX.exe file to XXX.alt(just a random extension) and put it on server. Now my code can download XXX.alt, but how can I change the file name from XXX.alt back to XXX.exe when in QT environment?

Nicholas Yu
  • 333
  • 1
  • 5
  • 7

4 Answers4

21

Use QFileInfo to get the path without the last extension then append the new extension.

QFileInfo info(fileName);
QString strNewName = info.path() + "/" + info.completeBaseName() + ".exe";
drescherjm
  • 10,365
  • 5
  • 44
  • 64
  • 1
    I think this needs a separator: `QString strNewName = info.path() + "/" + info.completeBaseName() + ".exe";` On Linux, the path returned from `QFileInfo::path()` does not include a separator at the end. – Mitch Nov 26 '16 at 13:52
  • @Mitch Thanks. Fixed. – drescherjm Nov 26 '16 at 14:26
1

Just use rename function from 'stdio.h'.

char oldname[] ="XXX.alt";
char newname[] ="XXX.exe";
result= rename( oldname , newname );
if ( result == 0 )
  puts ( "File successfully renamed" );
else
  perror( "Error renaming file" );
Ashot Khachatryan
  • 2,156
  • 2
  • 14
  • 30
  • 2
    In Qt this would be `QFile::rename(const QString & oldName, const QString & newName)` although the c code you posted should work fine. – drescherjm May 05 '15 at 14:08
  • both of you two are right. Thanks. and I found out we donot even need put the oldName. we can just QFile(const QString & newName) – Nicholas Yu May 06 '15 at 05:57
0

One solution is to find the last '.', and replace the substring from that position to the end with the substring you want.

Exactly how to do it, there are many ways using both std::string and QString, as both support finding characters in the string (and doing a search from the end to the beginning as well), and replace substrings.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Prefer to use baseName()

QFileInfo info(fileName);
QString strNewName = info.path() + info.baseName() + ".exe";

QString QFileInfo::completeBaseName () const
Returns file name with shortest extension removed (file.tar.gz -> file.tar)

QString QFileInfo::baseName () const
Returns file name with longest extension removed (file.tar.gz -> file)
Yash
  • 6,644
  • 4
  • 36
  • 26