Namespaces
Variants

std::experimental::filesystem:: rename

From cppreference.net
定义于头文件 <experimental/filesystem>
void rename ( const path & old_p, const path & new_p ) ;
void rename ( const path & old_p, const path & new_p, std:: error_code & ec ) ;
(文件系统 TS)

将文件系统对象从 old_p 移动或重命名至 new_p ,操作方式类似于 POSIX 的 rename

  • 如果 old_p 是非目录文件,则 new_p 必须是以下情况之一:
  • old_p 相同文件或为其硬链接:此情况下不执行任何操作。
  • 已存在的非目录文件:首先删除 new_p ,随后在不允许其他进程观察到 new_p 被删除的情况下,将路径名 new_p 链接至该文件,并解除 old_p 与文件的链接。需要同时具备包含 old_p 的目录和包含 new_p 的目录的写入权限。
  • 现有目录中的不存在的文件:将路径名 new_p 链接至该文件,并解除 old_p 与文件的链接。需要同时具备包含 old_p 的目录和包含 new_p 的目录的写入权限。
  • 如果 old_p 是目录,则 new_p 必须是以下情况之一:
  • old_p 相同目录或其硬链接:此情况下不执行任何操作。
  • 已存在的目录:在 POSIX 系统上,若 new_p 为空则会被删除,但在其他系统上可能视为错误。若未出错,则先删除 new_p ,随后在不允许其他进程观察到 new_p 被删除的状态下,将路径名 new_p 链接至该目录,同时解除 old_p 与目录的链接。需要同时具备包含 old_p 的目录和包含 new_p 的目录的写入权限。
  • 不存在的目录(不以目录分隔符结尾)且其父目录存在:将路径名 new_p 链接至该目录,同时解除 old_p 与目录的链接。需要同时具备包含 old_p 的目录和包含 new_p 的目录的写入权限。
  • 符号链接不会被跟随:如果 old_p 是符号链接,则重命名的是该链接本身而非其目标。如果 new_p 是已存在的符号链接,则删除的是该链接本身而非其目标。

重命名失败如果

  • new_p 点点 结尾。
  • new_p 指向一个以目录分隔符结尾的不存在的目录。
  • old_p 是一个目录,且为 new_p 的上级目录。

目录

参数

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

返回值

(无)

异常

The overload that does not take an error_code & parameter throws filesystem_error on underlying OS API errors, constructed with old_p as the first argument, new_p as the second argument, and the OS error code as the error code argument. std:: bad_alloc may be thrown if memory allocation fails. The overload taking an error_code & parameter sets it to the OS API error code if an OS API call fails, and executes ec. clear ( ) if no errors occur. This overload has
noexcept 规范:
noexcept

示例

#include <experimental/filesystem>
#include <fstream>
#include <iostream>
namespace fs = std::experimental::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"); // 正常
//  fs::rename(p/"from", p/"to"); // 错误:to 非空目录
    fs::rename(p/"from", p/"to/subdir"); // 正常
    fs::remove_all(p);
}

参见

重命名文件
(函数)
删除文件或空目录
递归删除文件或目录及其所有内容
(函数)