Create a directory for every element of a path if it does not exist

时光总嘲笑我的痴心妄想 提交于 2019-12-24 04:01:50

问题


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


来源:https://stackoverflow.com/questions/43940515/create-a-directory-for-every-element-of-a-path-if-it-does-not-exist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!