不像python大法新建单层目录可以调用os.mkdir, 新建多层目录可以调用os.makedirs
c++17以前新建目录会稍微麻烦点, 需要根据不同平台进行调用系统api来新建目录。
例如新建单层目录(上一级根目录已经存在的情况)
int createDir(const std::string& path)
{
#ifdef _WIN32
int ret = _mkdir(path.c_str());
#else
int ret = mkdir(path.c_str(), 0777);
#endif
return ret;
}
返回 0表示新建成功,-1代表失败(如果跟目录不存在则会返回 -1)
新建多层目录,eg: D:\test\demo\2022
windows下没有提供现有的api来直接新建多层目录,需要自己区分割 ‘\’ 或者 ‘/’来一级级的创建。
Posix标准系统的,也是一样的。
但是有个取巧的办法, 那就是调用系统命令来创建
void createDir(const std::string& path)
{
std::string _dir;
#ifdef _WIN32
_dir = "MD " + path;
#else
_dir = "mkdir -p " + path;
#endif
std::system(_dir.c_str());
}
调用示例:
int main()
{
int ret = -1;
#ifdef _WIN32
struct _stat buffer;
ret = _stat(path.c_str(), &buffer);
#else
struct stat buffer;
ret = stat(path.c_str(), &buffer);
#endif
if(ret){
if(createDir("D:\\demo\\2022") == 0) {
std::cout<<"create dir success"<<std::endl;
}
}
return 0;
}
c++17标准里包含了创建文件夹的库函数:std::filesystem::create_directory可以直接跨平台调用,无需调用后文所述的系统api,这极大方便了开发者。
包含在头文件
bool create_directory( const std::filesystem::path& p );
bool create_directory( const std::filesystem::path& p, std::error_code& ec ) noexcept;
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;
bool create_directories( const std::filesystem::path& p );
bool create_directories( const std::filesystem::path& p, std::error_code& ec );
调用示例:
#include
#include
#include
#include
namespace fs = std::filesystem;
int main()
{
fs::current_path(fs::temp_directory_path());
fs::create_directories("D:/demo/2022/a");
fs::create_directory("D:/demo/2022/b");
fs::permissions("D:/demo/2022/b", fs::perms::others_all, fs::perm_options::remove);
fs::create_directory("D:/demo/2022/c", "D:/demo/2022/d");
//fs::remove_all("D:/demo");
return 0;
}
参考文献:
[1]: https://en.cppreference.com/w/cpp/filesystem/create_directory