Namespaces
Variants

std::filesystem::directory_entry:: file_size

From cppreference.net
std:: uintmax_t file_size ( ) const ;
(1) (C++17以降)
std:: uintmax_t file_size ( std:: error_code & ec ) const noexcept ;
(2) (C++17以降)

ファイルサイズがこの directory_entry 内にキャッシュされている場合、キャッシュされた値を返します。それ以外の場合、以下を返します:

2) std:: filesystem :: file_size ( パス ( ) , エラーコード ) .

目次

パラメータ

ec - 例外を投げないオーバーロードにおけるエラー報告用の出力パラメータ

戻り値

参照先のファイルシステムオブジェクトのサイズ。

例外

noexcept でマークされていないオーバーロードは、 メモリ確保に失敗した場合 std::bad_alloc をスローする可能性があります。

1) 基盤となるOS APIエラーが発生した場合、 std::filesystem::filesystem_error をスローします。これは p を第一パス引数、OSエラーコードをエラーコード引数として構築されます。
2) オペレーティングシステムAPI呼び出しが失敗した場合、 std:: error_code & パラメータにOS APIエラーコードを設定し、エラーが発生しなかった場合は ec. clear ( ) を実行します。

指定されたディレクトリ内のファイル一覧と、人間が読みやすい形式でのファイルサイズを表示します。

#include <cmath>
#include <cstdint>
#include <filesystem>
#include <iostream>
struct HumanReadable
{
    std::uintmax_t size{};
    template<typename Os> friend Os& operator<<(Os& os, HumanReadable hr)
    {
        int i{};
        double mantissa = hr.size;
        for (; mantissa >= 1024.0; mantissa /= 1024.0, ++i)
        {}
        os << std::ceil(mantissa * 10.0) / 10.0 << i["BKMGTPE"];
        return i ? os << "B (" << hr.size << ')' : os;
    }
};
int main(int argc, const char* argv[])
{
    const auto dir = argc == 2 ? std::filesystem::path{argv[1]}
                               : std::filesystem::current_path();
    for (std::filesystem::directory_entry const& entry : 
         std::filesystem::directory_iterator(dir))
        if (entry.is_regular_file())
            std::cout << entry.path().filename() << " size: "
                      << HumanReadable{entry.file_size()} << '\n';
}

出力例:

"boost_1_73_0.tar.bz2" size: 104.2MB (109247910)
"CppCon 2018 - Jon Kalb “Copy Elision”.mp4" size: 15.7MB (16411990)
"cppreference-doc-20190607.tar.xz" size: 6.3MB (6531336)
"hana.hpp" size: 6.7KB (6807)

関連項目

(C++17)
ファイルのサイズを返す
(関数)