C++ 参考手册

位置:首页 > C++ 参考手册 >文件系统库 > 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 ,以第一 path 参数 target,第二 path 参数 link 和作为错误码参数的 OS 错误码构造。若 OS API 调用失败,则接受 std::error_code& 参数的重载设置该参数为 OS API 错误码,而若不出现错误则执行 ec.clear() 。若内存分配失败,则任何不标记为 noexcept 的重载可能抛出 std::bad_alloc

注意

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

某些文件系统不支持符号链接,无关乎操作系统,例如用于某些内存卡和闪存驱动器的 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)
确定文件属性
确定文件属性,检查符号链接目标
(函数)
获得符号链接的目标
(函数)
创建一个硬链接
(函数)