std::filesystem::directory_entry:: file_size
From cppreference.net
<
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)
|
返回文件的大小
(函数) |