std::filesystem::rename

定义于头文件 <filesystem>
void rename(const std::filesystem::path& old_p,

            const std::filesystem::path& new_p);
void rename(const std::filesystem::path& old_p,
            const std::filesystem::path& new_p,

            std::error_code& ec);
(C++17 起)

移动或重命名 old_p 所标识的文件系统对象到 new_p ,如同用 POSIX rename

若有如下情况则重命名失败

目录

参数

old_p - 要移动或重命名的路径
new_p - 移动/重命名操作的目标路径
ec - 不抛出重载中报告错误的输出参数

返回值

(无)

异常

不接受 std::error_code& 参数的重载在底层 OS API 错误时抛出 filesystem_error ,以第一参数 old_p,第二参数 new_p 和作为错误码参数的 OS 错误码构造。若内存分配失败则可能抛出 std::bad_alloc 。若 OS API 调用失败,则接受 std::error_code& 参数的重载设置该参数为 OS API 错误码,而若不出现错误则执行 ec.clear()

示例

#include <iostream>
#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
    fs::path p = fs::current_path() / "sandbox";
    fs::create_directories(p/"from");
    std::ofstream(p/"from/file1.txt").put('a');
    fs::create_directory(p/"to");
 
//    fs::rename(p/"from/file1.txt", p/"to/"); // 错误: to 是目录
    fs::rename(p/"from/file1.txt", p/"to/file2.txt"); // OK
//    fs::rename(p/"from", p/"to"); // 错误: to 非空
    fs::rename(p/"from", p/"to/subdir"); // OK
 
    fs::remove_all(p);
}


参阅

重命名文件
(函数)
(C++17)
(C++17)
移除一个文件或空目录
移除一个文件或递归地移除一个目录及其所有内容
(函数)

版本历史

  • (当前 | 先前) 2017年5月1日 (一) 02:27Fruderica讨论 | 贡献. . (3,453字节) (+3,453). . (以“{{cpp/filesystem/title|rename}} {{cpp/filesystem/navbar}} {{dcl begin}} {{dcl header | filesystem}} {{dcl | since=c++17 |1= void rename(const std::filesystem::path& ...”为内容创建页面)