命名空间
变体
操作

std::filesystem::resize_file

来自 cppreference.cn
 
 
 
定义于头文件 <filesystem>
void resize_file( const std::filesystem::path& p,
                  std::uintmax_t new_size );
(1) (C++17 起)
void resize_file( const std::filesystem::path& p,

                  std::uintmax_t new_size,

                  std::error_code& ec ) noexcept;
(2) (C++17 起)

更改由 p 命名的常规文件的大小,如同 POSIX truncate 一样:如果文件大小之前大于 new_size,则文件的剩余部分将被丢弃。如果文件之前小于 new_size,则文件大小将增加,并且新区域看起来像是用零填充的。

目录

[编辑] 参数

p - 要调整大小的路径
new_size - 文件现在将具有的大小
ec - 非抛出重载中用于错误报告的输出参数

[编辑] 返回值

(无)

[编辑] 异常

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

1) 在底层操作系统 API 错误时抛出 std::filesystem::filesystem_error,并使用 p 作为第一个路径参数和操作系统错误代码作为错误代码参数构造。
2) 如果操作系统 API 调用失败,则将 std::error_code& 参数设置为操作系统 API 错误代码,并且如果没有错误发生,则执行 ec.clear()

[编辑] 注解

在支持稀疏文件的系统上,增加文件大小不会增加它在文件系统上占用的空间:空间分配仅在将非零字节写入文件时发生。

[编辑] 示例

演示创建稀疏文件对可用空间的影响。

#include <filesystem>
#include <fstream>
#include <iostream>
#include <locale>
 
int main()
{
    auto p = std::filesystem::temp_directory_path() / "example.bin";
    std::ofstream{p}.put('a');
    std::cout.imbue(std::locale{"en_US.UTF8"});
    std::cout << "File size:  " << std::filesystem::file_size(p) << '\n'
              << "Free space: " << std::filesystem::space(p).free << '\n';
    std::filesystem::resize_file(p, 64*1024); // resize to 64 KB
    std::cout << "File size:  " << std::filesystem::file_size(p) << '\n'
              << "Free space: " << std::filesystem::space(p).free << '\n';
    std::filesystem::remove(p);
}

可能的输出

File size:  1
Free space: 42,954,108,928
File size:  65,536
Free space: 42,954,108,928

[编辑] 参见

(C++17)
返回文件的大小
(函数) [编辑]
(C++17)
确定文件系统上可用的可用空间
(函数) [编辑]