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 。
1) 抛出 std::filesystem::filesystem_error,构造时以 p 为第一路径实参并以OS 错误码为错误码实参。
若 OS API 调用失败,则 @2@ 设置 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) |
返回文件的大小 (函数) |