Namespaces
Variants

std::filesystem::directory_entry:: assign

From cppreference.net
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) オペレーティングシステム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

関連項目

内容を代入
(公開メンバ関数)