std::filesystem::create_symlink, std::filesystem::create_directory_symlink

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

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

                     std::error_code& ec );
(1) (C++17 起)
void create_directory_symlink( const std::filesystem::path& target,

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

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

创建符号链接 link ,其目标设为 target ,如同用 POSIX symlink() :路径名 target 可以非法或不存在。

一些操作系统要求符号链接的创建鉴别该链接是否到目录。可移植的代码应用 (2) 创建目录符号链接,而非 (1) ,即使 POSIX 系统不作区别。

目录

参数

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 系统。

类似硬链接,符号链接允许一个文件拥有多个逻辑名。硬链接的存在保证文件的存在,即使原始文件名被移除。符号链接无这种保障;实际上, target 参数所指名的文件不必在链接创建时存在。符号链接能跨越文件系统边界。

示例

#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
 
int main()
{
    fs::create_directories("sandbox/subdir");
    fs::create_symlink("target", "sandbox/sym1");
    fs::create_directory_symlink("subdir", "sandbox/sym2");
 
    for(auto it = fs::directory_iterator("sandbox"); it != fs::directory_iterator(); ++it)
        if(is_symlink(it->symlink_status()))
            std::cout << *it << "->" << read_symlink(*it) << '\n';
 
    fs::remove_all("sandbox");
}

可能的输出:

"sandbox/sym1"->"target"
"sandbox/sym2"->"subdir"

参阅

(C++17)
(C++17)
确定文件属性
确定文件属性,检查符号链接对象
(函数)
(C++17)
获得符号链接的目标
(函数)
创建一个硬链接
(函数)

版本历史

  • (当前 | 先前 2017年4月30日 (日) 20:11Fruderica讨论 | 贡献 . . (2,826字节) (+6). . (撤销)
  • 当前 | 先前 2017年4月30日 (日) 20:10Fruderica讨论 | 贡献 . . (2,820字节) (-18). . (撤销)
  • 当前 | 先前) 2017年4月30日 (日) 19:58Fruderica讨论 | 贡献. . (2,838字节) (+2,838). . (以“{{cpp/filesystem/title|create_symlink|create_directory_symlink}} {{cpp/filesystem/navbar}} {{dcl begin}} {{dcl header | filesystem}} {{dcl | num=1 | since=c++17| 1= ...”为内容创建页面)