std::filesystem::file_size
From cppreference.com
< cpp | filesystem
| ヘッダー <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 | - | 検査するパス |
| エラーコード | - | 例外を投げないオーバーロードでのエラー報告のための出力パラメータ |
[編集] 戻り値
ファイルのサイズ(バイト単位)。
[編集] 例外
noexcept とマークされていないオーバーロードは、メモリ割り当てが失敗した場合に std::bad_alloc をスローする可能性があります。
1) 基盤となるOS APIエラーが発生した場合、最初のパス引数としてp、エラーコード引数としてOSのエラーコードとともに構築されたstd::filesystem::filesystem_error を投げます。
[編集] 例
このコードを実行
#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) |
通常ファイルのサイズを切り詰めまたはゼロ埋めで変更する (関数) |
| (C++17) |
ファイルシステム上の利用可能な空き容量を決定する (関数) |
| ディレクトリエントリが参照するファイルのサイズを返します。 ( std::filesystem::directory_entry の public メンバ関数) |