std::filesystem::file_size

定义于头文件 <filesystem>
std::uintmax_t file_size( const std::filesystem::path& p );
std::uintmax_t file_size( const std::filesystem::path& p, std::error_code& ec );
(1) (C++17 起)

p 不存在则报告错误。

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

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

错误时不抛出重载返回 -1

目录

参数

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

返回值

文件大小,以字节计。

异常

不接受 std::error_code& 参数的重载在底层 OS API 错误时抛出 filesystem_error ,以第一参数 p 和作为错误码参数的 OS 错误码构造。若内存分配失败则可能抛出 std::bad_alloc 。若 OS API 调用失败,则接受 std::error_code& 参数的重载设置该参数为 OS API 错误码,而若不出现错误则执行 ec.clear()

示例

#include <iostream>
#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
    fs::path p = fs::current_path() / "example.bin";
    std::ofstream(p).put('a'); // 创建文件大小为 1
    std::cout << "File size = " << fs::file_size(p) << '\n';
    fs::remove(p);
 
    try {
        fs::file_size("/dev"); // 试图获取目录的大小
    } catch(fs::filesystem_error& e) {
        std::cout << e.what() << '\n';
    }        
}

可能的输出:

File size = 1
filesystem error: cannot get file size: Is a directory [/dev]

参阅

(C++17)
以截断或填充零更改一个常规文件的大小
(函数)
(C++17)
确定文件系统上的可用空闲空间
(函数)
返回 directory_entry 所指代的文件大小
(std::filesystem::directory_entry 的公开成员函数)

版本历史

  • (当前 | 先前 2017年11月4日 (六) 06:57Fruderica讨论 | 贡献. . (1,739字节) (0). . (fix output to match gcc's output for the TS) (撤销)
  • 当前 | 先前) 2017年5月1日 (一) 01:08Fruderica讨论 | 贡献. . (1,739字节) (+1,739). . (以“{{cpp/filesystem/title|file_size}} {{cpp/filesystem/navbar}} {{dcl begin}} {{dcl header | filesystem}} {{dcl | num=1 | since=c++17 | 1= std::uintmax_t file_size( con...”为内容创建页面)