Create a directory for every element of a path if it does not exist
c++, c++14, c++17, std
Solution
`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;
}
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;
}
Problem
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++?