std::filesystem::space
From cppreference.com
< 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 を呼び出したかのように決定します。
POSIX の struct statvfs のメンバから、以下のように設定された filesystem::space_info 型のオブジェクトを生成して返します。
-
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 | - | 検査するパス |
| エラーコード | - | 例外を投げないオーバーロードでのエラー報告のための出力パラメータ |
[編集] 戻り値
ファイルシステムの情報(filesystem::space_info オブジェクト)。
[編集] 例外
noexcept とマークされていないオーバーロードは、メモリ割り当てが失敗した場合に std::bad_alloc をスローする可能性があります。
1) 基盤となるOS APIエラーが発生した場合、最初のパス引数としてp、エラーコード引数としてOSのエラーコードとともに構築されたstd::filesystem::filesystem_error を投げます。
[編集] 注記
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) |
ファイルシステムの空き容量と利用可能容量に関する情報 (クラス) |