名稱空間
變體
操作

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<std::uintmax_t>(-1)

目錄

[編輯] 引數

p - 要檢查的路徑
ec - 非丟擲過載中用於錯誤報告的出參

[編輯] 返回值

檔案系統資訊(一個 filesystem::space_info 物件)。

[編輯] 異常

任何未標記為 noexcept 的過載都可能在記憶體分配失敗時丟擲 std::bad_alloc

1) 在底層作業系統 API 錯誤時丟擲 std::filesystem::filesystem_error,構造時以 p 作為第一個路徑引數,OS 錯誤碼作為錯誤碼引數。
2) 如果 OS API 呼叫失敗,則將 std::error_code& 引數設定為 OS API 錯誤碼;如果未發生錯誤,則執行 ec.clear()

[編輯] 注意

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

[編輯] 參閱

關於檔案系統空閒和可用空間的資訊
(類) [編輯]