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'; // 成功 std::cout << "remove(): " << fs::remove(tmp / O_O) << '\n'; // 失败 std::filesystem::create_directories(tmp / "abcdef/example"); const std::uintmax_t n{fs::remove_all(tmp / "abcdef")}; std::cout << "remove_all(): " << n << " 个文件或目录\n"; }
可能的输出:
remove(): true remove(): false remove_all(): 2 个文件或目录
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
---|---|---|---|
LWG 3014 | C++17 | remove_all 的 error_code 重载被标记为 noexcept 但能分配内存
|
移除 noexcept |
[编辑] 参阅
删除文件 (函数) |