如果路径中的每个元素都不存在,则创建一个目录 [英] Create a directory for every element of a path if it does not exist
问题描述
在C ++中,我想从路径 path / that / consists / of / several / elements
创建目录。我还想创建该目录的所有父目录,以防它们不存在。
In C++, I want to create a directory from a path "path/that/consists/of/several/elements"
. Also I want to create all parent directories of that directory in case they are not existing. How to do that with std C++?
推荐答案
std :: experimental ::文件系统
/ std :: filesystem
(C ++ 14 / C ++ 17)提供 create_directories()
。如果尚不存在,它将为每个路径元素创建一个目录。为此,它执行 create_directory()
中的每个这样的元素。
std::experimental::filesystem
/std::filesystem
(C++14/C++17) provides create_directories()
. It creates a directory for every path element if it does not already exist. For that it executes create_directory()
for every such element.
#include <experimental/filesystem>
#include <iostream>
int main()
{
namespace fs = std::experimental::filesystem; // In C++17 use std::filesystem.
try {
fs::create_directories("path/with/directories/that/might/not/exist");
}
catch (std::exception& e) { // Not using fs::filesystem_error since std::bad_alloc can throw too.
std::cout << e.what() << std::endl;
}
return 0;
}
如果异常处理不合适,请 std :: filesystem
函数使用 std :: error_code
:
If exception handling does not fit, std::filesystem
functions have overloads using std::error_code
:
int main() {
namespace fs = std::experimental::filesystem; // In C++17 use std::filesystem.
std::error_code ec;
bool success = fs::create_directories("path/with/directories/that/might/not/exist", ec);
if (!success) {
std::cout << ec.message() << std::endl; // Fun fact: In case of success ec.message() returns "The operation completed successfully." using vc++.
}
return 0;
}
这篇关于如果路径中的每个元素都不存在,则创建一个目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!