std::filesystem::create_directory, std::filesystem::create_directories_C++中文网
位置:首页 > C++ 参考手册 >文件系统库 > std::filesystem::create_directory, std::filesystem::create_directories
| 定义于头文件 |
||
| bool create_directory( const std::filesystem::path& p ); |
(1) | (C++17 起) |
| bool create_directory( const std::filesystem::path& p, const std::filesystem::path& existing_p ); |
(2) | (C++17 起) |
| bool create_directories( const std::filesystem::path& p ); |
(3) | (C++17 起) |
2) 同 (1) ,除了新目录的属性复制自 existing_p (必须是已存在的目录)。复制的属性是取决于操作系统:在 POSIX 系统上,如同按照下方复制属性
stat(existing_p.c_str(), &attributes_stat) mkdir(p.c_str(), attributes_stat.st_mode)
在 Windows 操作系统上,不复制 existing_p 的属性。
3) 对每个尚未存在的 p 的元素执行 (1) 。若 p 已存在,则函数不做任何事(不把此条件当做错误)。
参数
| p | - | 要创建的新目录的路径 |
| existing_p | - | 要自之复制属性的目录的路径 |
| ec | - | 不抛出重载中报告错误的输出参数 |
返回值
若创建了 p 所解析到的目录则为 true ,否则为 false 。
异常
注意
保持属性的重载 (2) 被 copy() 在递归地复制目录时隐式调用。其在 boost.filesystem 的等价物是 copy_directory (参数顺序相反)
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| DR | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 2935 | C++17 | 若目标已存在但非目录,则为错误 | 不再是错误 |
| LWG 3014 | C++17 | create_directories 的 error_code 重载被标记为 noexcept 但能分配内存
|
移除 noexcept |
| P1164R1 | C++17 | 已存在的非目录文件导致的创建失败不是错误 | 使之为错误 |
示例
#include <iostream> #include <fstream> #include <cstdlib> #include <filesystem> namespace fs = std::filesystem; int main() { fs::create_directories("sandbox/1/2/a"); fs::create_directory("sandbox/1/2/b"); fs::permissions("sandbox/1/2/b", fs::perms::others_all, fs::perm_options::remove); fs::create_directory("sandbox/1/2/c", "sandbox/1/2/b"); std::system("ls -l sandbox/1/2"); fs::remove_all("sandbox"); }
可能的输出:
drwxr-xr-x 2 user group 4096 Apr 15 09:33 a drwxr-x--- 2 user group 4096 Apr 15 09:33 b drwxr-x--- 2 user group 4096 Apr 15 09:33 c