std::filesystem::space
来自 cppreference.cn
< cpp | filesystem
定义于头文件 <filesystem> |
||
std::filesystem::space_info space( const std::filesystem::path& p ); |
(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 的成员设置如下
-
space_info.capacity
被设置为如同 f_blocks * f_frsize。 -
space_info.free
被设置为 f_bfree * f_frsize。 -
space_info.available
被设置为 f_bavail * f_frsize。 - 任何无法确定的成员都被设置为 static_cast<std::uintmax_t>(-1)。
不抛出异常的重载将所有成员设置为 static_cast<std::uintmax_t>(-1),若发生错误。
目录 |
[编辑] 参数
p | - | 要检查的路径 |
ec | - | 非抛出异常重载中用于错误报告的输出参数 |
[编辑] 返回值
文件系统信息(一个 filesystem::space_info
对象)。
[编辑] 异常
任何未标记 noexcept
的重载都可能在内存分配失败时抛出 std::bad_alloc。
[编辑] 注解
space_info.available
可能小于 space_info.free
。
[编辑] 示例
运行此代码
#include <cstdint> #include <filesystem> #include <iostream> #include <locale> 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
[编辑] 参见
(C++17) |
关于文件系统上可用和剩余空间的信息 (类) |