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++?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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;
}
回答2:
With Boost:
boost::filesystem::path dir(to create);
if(boost::filesystem::create_directories(dir)) {
std::cout << "Success" << "\n";
}
Or with platform dependent system
:
system("mkdir " + to_create);