C++ 参考手册

位置:首页 > C++ 参考手册 >文件系统库 > std::filesystem::create_directory, std::filesystem::create_directories

定义于头文件 <filesystem>
bool create_directory( const std::filesystem::path& p );
bool create_directory( const std::filesystem::path& p, std::error_code& ec ) noexcept;
(1) (C++17 起)
bool create_directory( const std::filesystem::path& p,

                       const std::filesystem::path& existing_p );
bool create_directory( const std::filesystem::path& p,
                       const std::filesystem::path& existing_p,

                       std::error_code& ec ) noexcept;
(2) (C++17 起)
bool create_directories( const std::filesystem::path& p );
bool create_directories( const std::filesystem::path& p, std::error_code& ec );
(3) (C++17 起)
1) 如同用 POSIX mkdir()static_cast<int>(std::filesystem::perms::all) 为第二参数创建目录 p (亲目录必须已经存在)。若该函数因为 p 解析到既存目录而失败,则不报告错误。否则在失败时报告错误。
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

异常

1,3) 不接受 std::error_code& 参数的重载在底层 OS API 错误时抛出 filesystem_error ,以第一 path 参数 p 和作为错误码参数的 OS 错误码构造。若 OS API 调用失败,则接受 std::error_code& 参数的重载设置该参数为 OS API 错误码,而若不出现错误则执行 ec.clear() 。若内存分配失败,则任何不标记为 noexcept 的重载可能抛出 std::bad_alloc
2) 不接受 std::error_code& 参数的重载在底层 OS API 错误时抛出 filesystem_error ,以第一 path 参数 p,第二 path 参数 existing_p 和作为错误码参数的 OS 错误码构造。若 OS API 调用失败,则接受 std::error_code& 参数的重载设置该参数为 OS API 错误码,而若不出现错误则执行 ec.clear() 。若内存分配失败,则任何不标记为 noexcept 的重载可能抛出 std::bad_alloc

注意

保持属性的重载 (2)copy() 在递归地复制目录时隐式调用。其在 boost.filesystem 的等价物是 copy_directory (参数顺序相反)

缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

DR 应用于 出版时的行为 正确行为
LWG 2935 C++17 若目标已存在但非目录,则为错误 不再是错误
LWG 3014 C++17 create_directorieserror_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

参阅

创建一个符号链接
(函数)
(C++17)
复制文件或目录
(函数)
(C++17)
标识文件系统权限
(枚举)