Namespaces
Variants

std::filesystem:: file_size

From cppreference.net
定义于头文件 <filesystem>
(1) (C++17 起)
(2) (C++17 起)

如果 p 不存在,将报告错误。

对于常规文件 p ,返回通过读取 POSIX stat 获取的结构体中的 st_size 成员所确定的大小(符号链接会被跟踪)。

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

非抛出重载在出错时返回 static_cast < std:: uintmax_t > ( - 1 )

目录

参数

p - 要检查的路径
ec - 非抛出重载中用于错误报告的输出参数

返回值

文件的大小,以字节为单位。

异常

任何未标记为 noexcept 的重载在内存分配失败时可能抛出 std::bad_alloc

1) 当底层操作系统 API 出错时抛出 std::filesystem::filesystem_error ,该异常以 p 作为第一个路径参数,以操作系统错误代码作为错误码参数构造。
2) 若操作系统API调用失败,将 std:: error_code & 参数设置为操作系统API错误码;若无错误发生,则执行 ec. clear ( )

示例

#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'); // 创建大小为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 (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)
尝试获取目录大小:
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)
确定文件系统上的可用空闲空间
(函数)
返回目录项所指向文件的大小
( std::filesystem::directory_entry 的公开成员函数)