std::filesystem:: space
|
定义于头文件
<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)
|
文件系统中可用空间和空闲空间的信息
(类) |