std::experimental::filesystem::file_size
来自 cppreference.cn
< cpp | experimental | fs
定义于头文件 <experimental/filesystem> |
||
std::uintmax_t file_size( const path& p ); std::uintmax_t file_size( const path& p, error_code& ec ); |
(1) | (filesystem TS) |
返回常规文件 p 的大小,其确定方式如同通过读取 POSIX stat 获取的结构中的 st_size
成员(符号链接被跟踪)。
试图确定目录(以及任何其他非常规文件或符号链接的文件)的大小被视为错误。
不抛出异常的重载在错误时返回 -1。
目录 |
[编辑] 参数
p | - | 要检查的路径 |
ec | - | 非抛出重载中用于错误报告的出参 |
[编辑] 返回值
文件大小,以字节为单位。
[编辑] 异常
不接受 error_code& 参数的重载在底层 OS API 错误时抛出 filesystem_error,该错误以 p 作为第一个参数,OS 错误码作为错误码参数构造。std::bad_alloc 可能在内存分配失败时抛出。接受 error_code& 参数的重载在 OS API 调用失败时将其设置为 OS API 错误码,并且在没有错误发生时执行 ec.clear()。此重载具有noexcept 规范:
noexcept
[编辑] 示例
运行此代码
#include <experimental/filesystem> #include <fstream> #include <iostream> namespace fs = std::experimental::filesystem; int main() { fs::path p = fs::current_path() / "example.bin"; std::ofstream(p).put('a'); // create file of size 1 std::cout << "File size = " << fs::file_size(p) << '\n'; fs::remove(p); try { fs::file_size("/dev"); // attempt to get size of a directory } catch (fs::filesystem_error& e) { std::cout << e.what() << '\n'; } }
可能的输出
File size = 1 filesystem error: cannot get file size: Is a directory [/dev]
[编辑] 参阅
通过截断或零填充更改常规文件的大小 (函数) | |
确定文件系统上可用的空闲空间 (函数) |