std::filesystem:: remove, std::filesystem:: remove_all
From cppreference.net
<
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
。
3,4)
返回被删除的文件和目录数量(若路径
p
原本不存在则可能为零)。接受
error_code&
参数的重载版本在出错时返回
static_cast
<
std::
uintmax_t
>
(
-
1
)
。
异常
任何未标记为
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; // 创建包含 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 << " files or directories\n"; }
可能的输出:
remove(): true remove(): false remove_all(): 2 files or directories
缺陷报告
下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
| 缺陷报告 | 适用范围 | 发布时的行为 | 正确行为 |
|---|---|---|---|
| LWG 3014 | C++17 |
error_code
重载的
remove_all
被标记为 noexcept 但可能分配内存
|
移除 noexcept |
另请参阅
|
删除文件
(函数) |