c++ how to create a directory from a path

前端 未结 5 1133
迷失自我
迷失自我 2020-12-20 15:06

what is a convenient way to create a directory when a path like this is given: \"\\server\\foo\\bar\\\"

note that the intermediate directories may not exist.

相关标签:
5条回答
  • 2020-12-20 15:46

    I'd write a loop. Split the path into components, and "walk it", i.e. starting at the beginning, check to see if it exists. If it does, enter it and continue. If it does not, create it, enter it and continue. For bonus points, detect if a component exists, but is a file rather than an a directory.

    0 讨论(0)
  • 2020-12-20 15:56

    SHCreateDirectoryEx() can do that. It's available on XP SP2 and newer versions of Windows.

    0 讨论(0)
  • 2020-12-20 16:03

    Since C++17:

    bool create_directories( const std::filesystem::path& p );
    bool create_directories( const std::filesystem::path& p, std::error_code& ec );
    

    More info: https://en.cppreference.com/w/cpp/filesystem/create_directory

    0 讨论(0)
  • 2020-12-20 16:05

    If you can use an external library, I'd look at boost::filesystem

    #include <boost/filesystem.hpp>
    namespace fs=boost::filesystem;
    
    int main(int argc, char** argv)
    {
        fs::create_directories("/some/path");
    }
    
    0 讨论(0)
  • 2020-12-20 16:05

    You can also use template bool create_directories(const Path & p) from Boost::Filesystem library. And it is available not only in Windows.

    0 讨论(0)
提交回复
热议问题