std::filesystem:: create_directory, std::filesystem:: create_directories
|
定义于头文件
<filesystem>
|
||
|
bool
create_directory
(
const
std::
filesystem
::
path
&
p
)
;
|
(1) | (C++17 起) |
|
bool
create_directory
(
const
std::
filesystem
::
path
&
p,
std::
error_code
&
ec
)
noexcept
;
|
(2) | (C++17 起) |
|
bool
create_directory
(
const
std::
filesystem
::
path
&
p,
const std:: filesystem :: path & existing_p ) ; |
(3) | (C++17 起) |
|
bool
create_directory
(
const
std::
filesystem
::
path
&
p,
const
std::
filesystem
::
path
&
existing_p,
|
(4) | (C++17 起) |
|
bool
create_directories
(
const
std::
filesystem
::
path
&
p
)
;
|
(5) | (C++17 起) |
|
bool
create_directories
(
const
std::
filesystem
::
path
&
p,
std::
error_code
&
ec
)
;
|
(6) | (C++17 起) |
mkdir()
创建目录
p
,第二个参数为
static_cast
<
int
>
(
std::
filesystem
::
perms
::
all
)
(父目录必须已存在)。若函数因
p
指向已存在的目录而失败,不会报错。其他情况下若失败则会报告错误。
stat(existing_p.c_str(), &attributes_stat) mkdir(p.c_str(), attributes_stat.st_mode)
目录 |
参数
| p | - | 要创建的新目录路径 |
| existing_p | - | 用于复制属性的源目录路径 |
| ec | - | 非抛出重载中用于错误报告的输出参数 |
返回值
如果为 p 解析的目录是新创建的,则为 true ;否则为 false 。
异常
任何未标记为
noexcept
的重载在内存分配失败时可能抛出
std::bad_alloc
。
注释
属性保留重载
(3,4)
在递归复制目录时会被
copy()
隐式调用。其在boost.filesystem中的等效函数是
copy_directory
(参数顺序相反)。
示例
#include <cassert> #include <cstdlib> #include <filesystem> int main() { std::filesystem::current_path(std::filesystem::temp_directory_path()); // 基本用法 std::filesystem::create_directories("sandbox/1/2/a"); std::filesystem::create_directory("sandbox/1/2/b"); // 目录已存在(返回false,无错误) assert(!std::filesystem::create_directory("sandbox/1/2/b")); // 权限复制用法 std::filesystem::permissions( "sandbox/1/2/b", std::filesystem::perms::others_all, std::filesystem::perm_options::remove ); std::filesystem::create_directory("sandbox/1/2/c", "sandbox/1/2/b"); std::system("ls -l sandbox/1/2"); std::system("tree sandbox"); std::filesystem::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
sandbox
└── 1
└── 2
├── a
├── b
└── c
缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的C++标准。
| 缺陷报告 | 适用范围 | 发布时的行为 | 正确行为 |
|---|---|---|---|
| LWG 2935 | C++17 | 目标已存在但不是目录时报错 | 不报错 |
| LWG 3014 | C++17 |
error_code
重载的
create_directories
标记为 noexcept 但可能分配内存
|
移除 noexcept |
| P1164R1 | C++17 | 因已存在的非目录文件导致的创建失败不算错误 | 改为错误 |
参见
|
(C++17)
(C++17)
|
创建符号链接
(函数) |
|
(C++17)
|
复制文件或目录
(函数) |
|
(C++17)
|
标识文件系统权限
(枚举) |