9

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.

CreateDirectory and mkdir only seem to create the last part of a directory and give an error otherwise.

the platform is windows, MSVC compiler.

thanks!

clamp
  • 33,000
  • 75
  • 203
  • 299

5 Answers5

23

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");
}
gnud
  • 77,584
  • 5
  • 64
  • 78
6

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

Ferruccio
  • 98,941
  • 38
  • 226
  • 299
  • 3
    Deprecated: "[This function is available through Windows XP Service Pack 2 (SP2) and Windows Server 2003. It might be altered or unavailable in subsequent versions of Windows.]" – Technophile Dec 22 '14 at 22:40
  • 2
    @Technophile - According to MSDN, `SHCreateDirectory` is deprecated after XP SP2 & Server 2003 (http://msdn.microsoft.com/en-us/library/bb762130(v=vs.85).aspx). It does not mention `SHCreateDirectoryEx` being deprecated. – Ferruccio Jan 02 '15 at 12:46
  • 2
    It seems currently SHCreateDirectory**Ex** is also deprecated: msdn.microsoft.com/en-us/library/bb762131(v=vs.85).aspx – sergiol Mar 10 '17 at 18:47
1

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • thanks, good idea. although i would expect a function in the winapi or the stl that does exactly this? – clamp Sep 03 '09 at 14:53
0

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

Dawid
  • 4,042
  • 2
  • 27
  • 30
0

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

Szyk Cech
  • 31
  • 5