std::filesystem::remove, std::filesystem::remove_all
来自 cppreference.cn
< 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 | - | 用于在非抛出重载中报告错误的 out-parameter。 |
[编辑] 返回值
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++ 标准。
DR | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 3014 | C++17 | remove_all 的 error_code 重载标记为 noexcept 但可能分配内存 |
noexcept 已移除 |
[编辑] 参见
擦除文件 (函数) |