Namespaces
Variants

std::filesystem:: file_size

From cppreference.net
ヘッダーで定義 <filesystem>
(1) (C++17以降)
(2) (C++17以降)

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'); // サイズ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 の公開メンバ関数)