Create a directory for every element of a path if

2019-07-09 03:01发布

问题:

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);