std::filesystem::space

来自cppreference.com
 
 
 
在标头 <filesystem> 定义
(1) (C++17 起)
std::filesystem::space_info space( const std::filesystem::path& p,
                                   std::error_code& ec ) noexcept;
(2) (C++17 起)

确定路径名 p 定位于其上的文件系统信息,如同用 POSIX statvfs

植入并返回一个 filesystem::space_info 类型的对象,从 POSIX struct statvfs 的如下成员设置:

不抛出重载在错误时设所有成员为 static_cast<uintmax_t>(-1)

参数

p - 要检验的路径
ec - 不抛出重载的报告错误的输出形参

返回值

文件系统信息(filesystem::space_info 对象)。

异常

若内存分配失败,则任何不标记为 noexcept 的重载可能抛出 std::bad_alloc

1) 抛出 std::filesystem::filesystem_error,构造时以 p 为第一路径实参并以OS 错误码为错误码实参。

若 OS API 调用失败,则 @2@ 设置 std::error_code& 形参

为 OS API 错误码,而未发生错误时则执行 ec.clear()

注解

space_info.available 可以小于或等于 space_info.free

示例

#include <cstdint>
#include <filesystem>
#include <iostream>
 
std::uintmax_t disk_usage_percent(const std::filesystem::space_info& si,
                                  bool is_privileged = false) noexcept
{
    if (constexpr std::uintmax_t X(-1);
        si.capacity == 0 || si.free == 0 || si.available == 0 ||
        si.capacity == X || si.free == X || si.available == X
    )
        return 100;
 
    std::uintmax_t unused_space = si.free, capacity = si.capacity;
    if (!is_privileged)
    {
        const std::uintmax_t privileged_only_space = si.free - si.available;
        unused_space -= privileged_only_space;
        capacity -= privileged_only_space;
    }
    const std::uintmax_t used_space{capacity - unused_space};
    return 100 * used_space / capacity;
}
 
void print_disk_space_info(auto const& dirs, int width = 14)
{
    (std::cout << std::left).imbue(std::locale("en_US.UTF-8"));
 
    for (const auto s : {"Capacity", "Free", "Available", "Use%", "Dir"})
        std::cout << "│ " << std::setw(width) << s << ' ';
 
    for (std::cout << '\n'; auto const& dir : dirs)
    {
        std::error_code ec;
        const std::filesystem::space_info si = std::filesystem::space(dir, ec);
        for (auto x : {si.capacity, si.free, si.available, disk_usage_percent(si)})
            std::cout << "│ " << std::setw(width) << static_cast<std::intmax_t>(x) << ' ';
        std::cout << "│ " << dir << '\n';
    }
}
 
int main()
{
    const auto dirs = {"/dev/null", "/tmp", "/home", "/proc", "/null"};
    print_disk_space_info(dirs);
}

可能的输出:

│ Capacity       │ Free           │ Available      │ Use%           │ Dir            
│ 84,417,331,200 │ 42,732,986,368 │ 40,156,028,928 │ 50             │ /dev/null
│ 84,417,331,200 │ 42,732,986,368 │ 40,156,028,928 │ 50             │ /tmp
│ -1             │ -1             │ -1             │ 100            │ /home
│ 0              │ 0              │ 0              │ 100            │ /proc
│ -1             │ -1             │ -1             │ 100            │ /null

参阅

关于文件系统上空闲及可用空间的信息
(类)