Namespaces
Variants

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

From cppreference.net
定义于头文件 <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) 当底层操作系统 API 出错时抛出 std::filesystem::filesystem_error ,构造时以 target 作为第一个路径参数, link 作为第二个路径参数,并将操作系统错误代码作为错误码参数。
2,4) 若操作系统 API 调用失败,将 std:: error_code & 参数设置为操作系统 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)
确定文件属性
确定文件属性,检查符号链接目标
(函数)
获取符号链接的目标
(函数)
创建硬链接
(函数)