📜  如何在 cpp 中重命名文件 - C++ (1)

📅  最后修改于: 2023-12-03 14:52:15.953000             🧑  作者: Mango

如何在 C++ 中重命名文件

在 C++ 中,可以使用以下方法重命名文件:

1. 使用 rename 函数
#include <iostream>
#include <cstdio>

int main() {
    const char* oldname = "oldfile.txt";
    const char* newname = "newfile.txt";

    int result = std::rename(oldname, newname);

    if (result == 0) {
        std::cout << "文件重命名成功。" << std::endl;
    } else {
        std::cout << "文件重命名失败。" << std::endl;
    }

    return 0;
}

上述代码中,rename 函数用于将名为 oldfile.txt 的文件重命名为 newfile.txt。如果重命名成功,rename 函数返回零;否则返回非零值。

2. 使用 std::filesystem 库

从 C++17 开始,使用 std::filesystem 库可以更简单地重命名文件。

#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main() {
    const fs::path oldpath("oldfile.txt");
    const fs::path newpath("newfile.txt");

    try {
        fs::rename(oldpath, newpath);
        std::cout << "文件重命名成功。" << std::endl;
    } catch (const std::filesystem::filesystem_error& e) {
        std::cout << "文件重命名失败:" << e.what() << std::endl;
    }

    return 0;
}

上述代码中,std::filesystem::rename 函数用于将名为 oldfile.txt 的文件重命名为 newfile.txt。如果重命名失败,会抛出 std::filesystem::filesystem_error 异常,我们可以通过捕捉该异常来处理重命名失败的情况。

注意事项
  • 在使用 rename 函数或 std::filesystem::rename 函数时,需要确保原文件和目标文件位于同一文件系统中。
  • 在重命名文件之前,请确保你有足够的权限来修改目标文件所在的目录。

以上就是在 C++ 中重命名文件的方法,你可以根据自己的需要选择适合的方法进行操作。