📅  最后修改于: 2023-12-03 14:52:15.953000             🧑  作者: Mango
在 C++ 中,可以使用以下方法重命名文件:
#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
函数返回零;否则返回非零值。
从 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++ 中重命名文件的方法,你可以根据自己的需要选择适合的方法进行操作。