std::filesystem::resize_file

定义于头文件 <filesystem>
void resize_file(const std::filesystem::path& p,

                 std::uintmax_t new_size);
void resize_file(const std::filesystem::path& p,
                 std::uintmax_t new_size,

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

更改 p 所指名的的常规文件大小,如同用 POSIX truncate :若先前的文件大小大于 new_size ,则文件的剩余部分被舍弃。若先前的文件大小小于 new_size ,则增加文件大小,而且新区域如同以零填充。

目录

参数

p - 要重设大小的路径
new_size - 文件将会拥有的大小
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 <iomanip>
#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
    fs::path p = fs::current_path() / "example.bin";
    std::ofstream(p).put('a');
    std::cout << "File size: " << std::setw(10) << fs::file_size(p)
              << " Free space: " << fs::space(p).free << '\n';
    fs::resize_file(p, 1024*1024*1024); // 重设大小为 1 G
    std::cout << "File size: " << fs::file_size(p)
              << " Free space: " << fs::space(p).free << '\n';
    fs::remove(p);
}

可能的输出:

File size:          1 Free space: 3724541952
File size: 1073741824 Free space: 3724476416

参阅

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

版本历史

  • (当前 | 先前 2017年9月25日 (一) 04:34Fruderica讨论 | 贡献 . . (2,037字节) (+9). . (noexcept) (撤销)
  • 当前 | 先前) 2017年5月1日 (一) 01:31Fruderica讨论 | 贡献. . (2,028字节) (+2,028). . (以“{{cpp/filesystem/title|resize_file}} {{cpp/filesystem/navbar}} {{dcl begin}} {{dcl header | filesystem}} {{dcl | since=c++17 |1= void resize_file(const std::filesyst...”为内容创建页面)