Fail to rename a file in Qt with QDir::rename()

SamuelNLP picture SamuelNLP · Mar 14, 2013 · Viewed 8k times · Source

I'm using QDir::rename() to rename a temporary file.

here's my code:

// change the temporary filename
void save::finish()
{
    QString newpath = ui->path->text();

    QString newname = ui->filename->text();

    newpath.append("/");
    newpath.append(newname);
    newpath.append(".txt");

    QDir r;

    bool check = r.rename("temp.txt", newname);

    if (check == true)
    {
        QMessageBox::warning(this,"Error","Saved successfully!", QMessageBox::Ok);
        close();
    }

    else
    {
        QMessageBox::warning(this,"Error","Error saving! Please try again.", QMessageBox::Ok);
    }
}

the file is renamed but it stays in the same directory as the temporary file. I don't get what's wrong.

Answer

Viv picture Viv · Mar 14, 2013

Maybe try

bool check = r.rename("temp.txt", newpath);

I see you have a QString called newpath that is not used in the rename call but you pass newname which you've appended to newpath just in the previous line. From code you've posted looks like your just giving a new name and hence why the result file is in the same folder as the original but did get renamed.

Do remember that even with giving a full path QDir::rename will fail if source and destination path's are not on the same partition or for a few more reasons as mentioned in the documentation.