命名空间
变体
操作

std::filesystem::directory_entry::assign

来自 cppreference.cn
 
 
 
 
void assign( const std::filesystem::path& p );
(1) (since C++17)
void assign( const std::filesystem::path& p, std::error_code& ec );
(2) (since C++17)

为目录条目对象分配新内容。将路径设置为 p 并调用 refresh 以更新缓存的属性。如果发生错误,缓存属性的值将是未指定的。

此函数不会向文件系统提交任何更改。

目录

[编辑] 参数

p - 目录条目将引用的文件系统对象的路径
ec - 非抛出重载中用于错误报告的输出参数

[编辑] 返回值

(无)

[编辑] 异常

任何未标记为 noexcept 的重载都可能在内存分配失败时抛出 std::bad_alloc

1) 在底层操作系统 API 错误时抛出 std::filesystem::filesystem_error,使用 p 作为第一个路径参数,操作系统错误代码作为错误代码参数构建。
2) 如果操作系统 API 调用失败,则将 std::error_code& 参数设置为操作系统 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

[编辑] 参见

分配内容
(公共成员函数) [编辑]