std::filesystem::create_hard_link

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

                       const path& std::filesystem::link );
void create_hard_link( const std::filesystem::path& target,
                       const path& std::filesystem::link,

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

创建硬链接 link ,将其目标设为 target ,如同用 POSIX link() :路径名 target 必须存在。

一旦创建, linktarget 就是指代同一文件的二个逻辑名(它们等价)。即使原名 target 被删除,文件也会继续存在,并可以 link 访问。

目录

参数

target - 要链接到的文件或目录名
link - 新硬链接的路径
ec - 不抛出重载中报告错误的输出参数

返回值

(无)

异常

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

注意

一些操作系统完全不支持硬链接,或仅对常规文件支持。

某些文件系统不支持符号链接,无关乎操作系统,例如用于某些内存卡和闪存驱动器的 FAT 系统。

某些文件系统限制每个文件的链接数。

典型的到目录的硬链接对超级用户限制。

典型的硬链接不能跨越文件系统边界。

特殊路径名点(".")是到其亲目录的硬链接。特殊路径名双点("..")是到其亲目录的亲目录的硬链接。

示例

#include <iostream>
#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;
 
int main()
{
    fs::create_directories("sandbox/subdir");
    std::ofstream("sandbox/a").put('a'); // 创建常规文件
    fs::create_hard_link("sandbox/a", "sandbox/b");
    fs::remove("sandbox/a");
    // 通过存活的硬链接读取原始文件
    char c = std::ifstream("sandbox/b").get();
    std::cout << c << '\n';
    fs::remove_all("sandbox");
}

输出:

a

参阅

创建一个符号链接
(函数)
返回引用到指定文件的硬链接数
(函数)

版本历史

  • (当前 | 先前) 2017年4月30日 (日) 20:19Fruderica讨论 | 贡献. . (2,342字节) (+2,342). . (以“{{cpp/filesystem/title|create_hard_link}} {{cpp/filesystem/navbar}} {{dcl begin}} {{dcl header | filesystem}} {{dcl | since=c++17 | 1= void create_hard_link( const s...”为内容创建页面)