名稱空間
變體
操作

std::filesystem::directory_entry::assign

來自 cppreference.com
 
 
 
 
void assign( const std::filesystem::path& p );
(1) (C++17 起)
void assign( const std::filesystem::path& p, std::error_code& ec );
(2) (C++17 起)

將新內容分配給目錄項物件。將路徑設定為 p 並呼叫 refresh 以更新快取屬性。如果發生錯誤,快取屬性的值未指定。

此函式不會對檔案系統提交任何更改。

目錄

[編輯] 引數

p - 目錄項將引用的檔案系統物件的路徑
ec - 非丟擲過載中用於錯誤報告的出參

[編輯] 返回值

(無)

[編輯] 異常

任何未標記為 noexcept 的過載都可能在記憶體分配失敗時丟擲 std::bad_alloc

1) 在底層 OS API 錯誤時丟擲 std::filesystem::filesystem_error,構造時以 p 作為第一個路徑引數,OS 錯誤碼作為錯誤碼引數。
2) 如果 OS API 呼叫失敗,則將 std::error_code& 引數設定為 OS API 錯誤碼;如果沒有錯誤發生,則執行 ec.clear()

[編輯] 示例

#include <filesystem>
#include <fstream>
#include <iostream>
 
void print_entry_info(const std::filesystem::directory_entry& entry)
{
    if (std::cout << "The entry " << entry; not entry.exists())
    {
        std::cout << " does not exists on the file system\n";
        return;
    }
    std::cout << " is ";
    if (entry.is_directory())
        std::cout << "a directory\n";
    if (entry.is_regular_file())
        std::cout << "a regular file\n";
    /*...*/
}
 
int main()
{
    std::filesystem::current_path(std::filesystem::temp_directory_path());
 
    std::filesystem::directory_entry entry{std::filesystem::current_path()};
    print_entry_info(entry);
 
    std::filesystem::path name{"cppreference.html"};
    std::ofstream{name} << "C++";
 
    std::cout << "entry.assign();\n";
    entry.assign(entry/name);
    print_entry_info(entry);
 
    std::cout << "remove(entry);\n";
    std::filesystem::remove(entry);
    print_entry_info(entry); // the entry still contains old "state"
 
    std::cout << "entry.assign();\n";
    entry.assign(entry); // or just call entry.refresh()
    print_entry_info(entry);
}

可能的輸出

The entry "/tmp" is a directory
entry.assign();
The entry "/tmp/cppreference.html" is a regular file
remove(entry);
The entry "/tmp/cppreference.html" is a regular file
entry.assign();
The entry "/tmp/cppreference.html" does not exists on the file system

[編輯] 參閱

賦值內容
(public member function) [編輯]