名稱空間
變體
操作

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

來自 cppreference.com
 
 
 
定義於標頭檔案 <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) [編輯]