名前空間
変種
操作

std::filesystem::directory_entry::file_size

From cppreference.com
 
 
 
 
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にファイルサイズがキャッシュされている場合は、キャッシュされた値を返します。それ以外の場合は、以下を返します。

目次

[編集] パラメータ

エラーコード - 例外を投げないオーバーロードでのエラー報告のための出力パラメータ

[編集] 戻り値

参照されているファイルシステムオブジェクトのサイズ。

[編集] 例外

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

1) 基盤となるOS APIエラーが発生した場合、最初のパス引数としてp、エラーコード引数としてOSのエラーコードとともに構築されたstd::filesystem::filesystem_error を投げます。
2) OS 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)
ファイルのサイズを返す
(関数) [編集]
English 日本語 中文(简体) 中文(繁體)