std::filesystem::file_size

来自cppreference.com
 
 
 
在标头 <filesystem> 定义
(1) (C++17 起)
std::uintmax_t file_size(conststd::filesystem::path& p,
                          std::error_code& ec )noexcept;
(2) (C++17 起)

p 不存在则报告错误。

对于常规文件 p,返回其大小,如同以读取由 POSIX stat 获得的结构体的 st_size 成员确定(跟随符号链接)。

尝试确定目录(以及其他非常规文件或符号链接)的大小的结果是实现定义的。

发生错误时不抛出重载返回 static_cast<std::uintmax_t>(-1)

目录

[编辑]参数

p - 要检验的路径
ec - 不抛出重载中报告错误的输出形参

[编辑]返回值

文件大小,以字节计。

[编辑]异常

若内存分配失败,则任何不标记为 noexcept 的重载可能抛出 std::bad_alloc

1) 抛出 std::filesystem::filesystem_error,构造时以 p 为第一路径实参并以OS 错误码为错误码实参。
2) 若 OS API 调用失败,则设置 std::error_code& 为 OS API 错误码,而未发生错误时则执行 ec.clear()

[编辑]示例

#include <cmath>#include <filesystem>#include <fstream>#include <iostream>namespace fs = std::filesystem;   struct HumanReadable {std::uintmax_t size{};   private:friendstd::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, charconst* argv[]){ fs::path example ="example.bin"; fs::path p = fs::current_path()/ example;std::ofstream(p).put('a');// 创建大小为 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<<"尝试获取目录的大小:\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(conststd::uintmax_t size = fs::file_size(bin, ec); ec)std::cout<< bin <<" : "<< ec.message()<<'\n';elsestd::cout<< bin <<" size = "<< HumanReadable{size}<<'\n';}}

可能的输出:

"example.bin" size = 1 "./a.out" size = 22KB (22512) 尝试获取目录的大小: 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)
确定文件系统上的可用空闲空间
(函数)[编辑]
返回 directory_entry 所指代的文件大小
(std::filesystem::directory_entry 的公开成员函数)[编辑]
close