命名空间
变体
操作

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) 在底层操作系统 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)
确定文件属性
确定文件属性,检查符号链接目标
(function) [编辑]
获取符号链接的目标
(function) [编辑]
创建硬链接
(function) [编辑]