std::filesystem::directory_entry::file_size
來自 cppreference.com
< cpp | filesystem | directory_entry
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
,則返回快取值。否則,返回
1) std::filesystem::file_size(path()),
2) std::filesystem::file_size(path(), ec)。
目錄 |
[編輯] 引數
ec | - | 非丟擲過載中用於錯誤報告的出參 |
[編輯] 返回值
所指檔案系統物件的大小。
[編輯] 異常
任何未標記為 noexcept
的過載都可能在記憶體分配失敗時丟擲 std::bad_alloc。
[編輯] 示例
列印給定目錄中檔案的列表及其以人類可讀形式表示的大小。
執行此程式碼
#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) |
返回檔案大小 (函式) |