std::filesystem::remove, std::filesystem::remove_all
來自 cppreference.com
< cpp | filesystem
定義於標頭檔案 <filesystem> |
||
bool remove( const std::filesystem::path& p ); |
(1) | (C++17 起) |
bool remove( const std::filesystem::path& p, std::error_code& ec ) noexcept; |
(2) | (C++17 起) |
std::uintmax_t remove_all( const std::filesystem::path& p ); |
(3) | (C++17 起) |
std::uintmax_t remove_all( const std::filesystem::path& p, std::error_code& ec ); |
(4) | (C++17 起) |
目錄 |
[編輯] 引數
p | - | 要刪除的路徑 |
ec | - | 用於在不丟擲異常的過載中報告錯誤的輸出引數。 |
[編輯] 返回值
1,2) 如果檔案被刪除則為 true,如果檔案不存在則為 false。接受
error_code&
引數的過載在錯誤時返回 false。[編輯] 異常
任何未標記為 noexcept
的過載都可能在記憶體分配失敗時丟擲 std::bad_alloc。
[編輯] 注意
在 POSIX 系統上,此函式通常會根據需要呼叫 unlink
和 rmdir
,在 Windows 上呼叫 DeleteFileW
和 RemoveDirectoryW
。
如果 p 不存在,此函式返回 false 且不報告錯誤。
[編輯] 示例
執行此程式碼
#include <cstdint> #include <filesystem> #include <fstream> #include <iostream> int main() { namespace fs = std::filesystem; std::cout << std::boolalpha; fs::path tmp{std::filesystem::temp_directory_path()}; const auto O_O{"O_O"}; std::ofstream{tmp / O_O} << O_O; // creates file containing O_O std::cout << "remove(): " << fs::remove(tmp / O_O) << '\n'; // success std::cout << "remove(): " << fs::remove(tmp / O_O) << '\n'; // fail std::filesystem::create_directories(tmp / "abcdef/example"); const std::uintmax_t n{fs::remove_all(tmp / "abcdef")}; std::cout << "remove_all(): " << n << " files or directories\n"; }
可能的輸出
remove(): true remove(): false remove_all(): 2 files or directories
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 3014 | C++17 | remove_all 的 error_code 過載被標記為 noexcept 但可以分配記憶體 |
noexcept 已移除 |
[編輯] 參閱
擦除檔案 (函式) |