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) | (文件系统 TS) |
返回常规文件 p 的大小,其确定方式如同读取 POSIX stat 获取的结构体的 st_size
成员(符号链接会被追踪)。
尝试确定目录的大小(以及任何其他非常规文件或符号链接的文件)将被视为错误。
非抛出重载在错误时返回 -1。
目录 |
[编辑] 参数
p | - | 要检查的路径 |
ec | - | 非抛出重载中用于错误报告的输出参数 |
[编辑] 返回值
文件的字节大小。
[编辑] 异常
不接受 error_code& 参数的重载会在底层操作系统 API 错误时抛出 filesystem_error,并使用 p 作为首个参数,操作系统错误代码作为错误代码参数构造。 如果内存分配失败,可能会抛出 std::bad_alloc。 接受 error_code& 参数的重载会在操作系统 API 调用失败时将其设置为操作系统 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]
[编辑] 参见
通过截断或零填充更改常规文件的大小 (函数) | |
确定文件系统上的可用空间 (函数) |