未能将Qt中的文件重命名为QDir::rename()

时间:2021-04-01 19:29:04

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

我使用QDir::rename()来重命名一个临时文件。

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.

该文件被重命名,但它与临时文件保持在同一个目录中。我不明白是怎么回事。

1 个解决方案

#1


3  

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.

我看到你有一个QString,叫做newpath,它不在重命名调用中使用,但是你传递的newname是你在前一行中添加到newpath的。从你发布的代码看来,你只是给了一个新名字,因此,为什么结果文件和原来的文件夹一样,但确实被重命名了。

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.

请记住,即使给出了完整的路径QDir::如果源路径和目标路径不在同一个分区上,或者在文档中提到的一些原因,重命名将会失败。

#1


3  

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.

我看到你有一个QString,叫做newpath,它不在重命名调用中使用,但是你传递的newname是你在前一行中添加到newpath的。从你发布的代码看来,你只是给了一个新名字,因此,为什么结果文件和原来的文件夹一样,但确实被重命名了。

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.

请记住,即使给出了完整的路径QDir::如果源路径和目标路径不在同一个分区上,或者在文档中提到的一些原因,重命名将会失败。