名稱空間
變體
操作

std::filesystem::file_size

來自 cppreference.com
 
 
 
定義於標頭檔案 <filesystem>
std::uintmax_t file_size( const std::filesystem::path& p );
(1) (C++17 起)
std::uintmax_t file_size( const std::filesystem::path& p,
                          std::error_code& ec ) noexcept;
(2) (C++17 起)

如果 p 不存在,則報告錯誤。

對於常規檔案 p,返回透過讀取 POSIX stat 獲取的結構的 st_size 成員所確定的檔案大小(符號連結會被跟隨)。

嘗試確定目錄(以及任何其他不是常規檔案或符號連結的檔案)大小的結果是實現定義的。

非丟擲過載在發生錯誤時返回 static_cast<std::uintmax_t>(-1)

目錄

[編輯] 引數

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

[編輯] 返回值

檔案大小,以位元組為單位。

[編輯] 異常

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

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

[編輯] 示例

#include <cmath>
#include <filesystem>
#include <fstream>
#include <iostream>
namespace fs = std::filesystem;
 
struct HumanReadable
{
    std::uintmax_t size{};
 
private:
    friend std::ostream& operator<<(std::ostream& os, HumanReadable hr)
    {
        int o{};
        double mantissa = hr.size;
        for (; mantissa >= 1024.; mantissa /= 1024., ++o);
        os << std::ceil(mantissa * 10.) / 10. << "BKMGTPE"[o];
        return o ? os << "B (" << hr.size << ')' : os;
    }
};
 
int main(int, char const* argv[])
{
    fs::path example = "example.bin";
    fs::path p = fs::current_path() / example;
    std::ofstream(p).put('a'); // create file of size 1
    std::cout << example << " size = " << fs::file_size(p) << '\n';
    fs::remove(p);
 
    p = argv[0];
    std::cout << p << " size = " << HumanReadable{fs::file_size(p)} << '\n';
 
    try
    {
        std::cout << "Attempt to get size of a directory:\n";
        [[maybe_unused]] auto x_x = fs::file_size("/dev");
    }
    catch (fs::filesystem_error& e)
    {
        std::cout << e.what() << '\n';
    }
 
    for (std::error_code ec; fs::path bin : {"cat", "mouse"})
    {
        bin = "/bin"/bin;
        if (const std::uintmax_t size = fs::file_size(bin, ec); ec)
            std::cout << bin << " : " << ec.message() << '\n';
        else
            std::cout << bin << " size = " << HumanReadable{size} << '\n';
    }
}

可能的輸出

"example.bin" size = 1
"./a.out" size = 22KB (22512)
Attempt to get size of a directory:
filesystem error: cannot get file size: Is a directory [/dev]
"/bin/cat" size = 50.9KB (52080)
"/bin/mouse" : No such file or directory

[編輯] 參閱

透過截斷或零填充更改常規檔案的大小
(函式) [編輯]
(C++17)
確定檔案系統上可用的空閒空間
(函式) [編輯]
返回目錄條目所引用的檔案的大小
(std::filesystem::directory_entry 的公有成員函式) [編輯]