命名空间
变体
操作

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

来自 cppreference.cn
 
 
 
定义于头文件 <filesystem>
void create_symlink( const std::filesystem::path& target,
                     const std::filesystem::path& link );
(1) (始于 C++17)
void create_symlink( const std::filesystem::path& target,

                     const std::filesystem::path& link,

                     std::error_code& ec ) noexcept;
(2) (始于 C++17)
void create_directory_symlink( const std::filesystem::path& target,
                               const std::filesystem::path& link );
(3) (始于 C++17)
void create_directory_symlink( const std::filesystem::path& target,

                               const std::filesystem::path& link,

                               std::error_code& ec ) noexcept;
(4) (始于 C++17)

创建一个符号链接 link,其目标设置为 target,如同 POSIX symlink():路径名 target 可能是无效的或不存在的。

某些操作系统要求符号链接创建时标识该链接指向目录。可移植代码应使用 (3,4) 创建目录符号链接,而不是 (1,2),即使在 POSIX 系统上没有区别。

目录

[编辑] 参数

target - 符号链接指向的路径,不必存在
link - 新符号链接的路径
ec - 非抛出重载中的错误报告输出参数

[编辑] 返回值

(无)

[编辑] 异常

任何未标记 noexcept 的重载都可能在内存分配失败时抛出 std::bad_alloc

1,3) 在底层 OS API 错误时抛出 std::filesystem::filesystem_error,使用 target 作为第一个路径参数, link 作为第二个路径参数,以及 OS 错误代码作为错误代码参数构造。
2,4) 如果 OS API 调用失败,则将 std::error_code& 参数设置为 OS API 错误代码;如果没有错误发生,则执行 ec.clear()

[编辑] 注解

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

某些文件系统不支持符号链接,无论操作系统如何,例如某些存储卡和闪存驱动器上使用的 FAT 系统。

与硬链接类似,符号链接允许一个文件有多个逻辑名称。硬链接的存在保证了文件的存在,即使原始名称已被删除。符号链接不提供这种保证;事实上,当链接创建时,target 参数命名的文件不必存在。符号链接可以跨越文件系统边界。

[编辑] 示例

#include <cassert>
#include <filesystem>
#include <iostream>
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';
 
    assert(std::filesystem::equivalent("sandbox/sym2", "sandbox/subdir"));
    fs::remove_all("sandbox");
}

可能的输出

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

[编辑] 参见

(C++17)(C++17)
确定文件属性
确定文件属性,检查符号链接目标
(函数) [编辑]
获取符号链接的目标
(函数) [编辑]
创建硬链接
(函数) [编辑]