std::filesystem::resize_file
來自 cppreference.com
< cpp | filesystem
定義於標頭檔案 <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, |
(2) | (C++17 起) |
更改由 p 命名的常規檔案的大小,如同透過 POSIX truncate
:如果檔案大小以前大於 new_size,則檔案的其餘部分將被丟棄。如果檔案以前小於 new_size,則檔案大小會增加,新區域將顯示為零填充。
目錄 |
[編輯] 引數
p | - | 要調整大小的路徑 |
new_size | - | 檔案現在將擁有的大小 |
ec | - | 非丟擲過載中用於錯誤報告的出參 |
[編輯] 返回值
(無)
[編輯] 異常
任何未標記為 noexcept
的過載都可能在記憶體分配失敗時丟擲 std::bad_alloc。
[編輯] 注意
在支援稀疏檔案的系統上,增加檔案大小不會增加它在檔案系統上佔用的空間:空間分配僅在向檔案寫入非零位元組時發生。
[編輯] 示例
演示建立稀疏檔案對可用空間的影響。
執行此程式碼
#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) |
確定檔案系統上可用的空閒空間 (函式) |