I'm trying to create a function that takes the name of a directory (C:\foo\bar
, or ..\foo\bar\..\baz
, or \\someserver\foo\bar
), and creates directories as necessary so that the whole path is created.
I am attempting a pretty naive implementation of this myself and it seems to be a string processing nightmare. There is /
vs \
, there is the special case of network shares which begin with \\
(also you can't attempt to mkdir() the first two levels of the path which are machine name and share name), and there is \.\
type nonsense that can exist in a path.
Does there exist a simple way to do this in C++?
for /f - Loop command against the results of another command. md - Make Directory - Creates a new folder. pushd - Change the current directory/folder and store the previous folder/path for use by the POPD command. popd - Change directory back to the path/folder most recently stored by the PUSHD command.
Create an object of the File class with md as a parameter. Check if the directory already exists using the exists() method and display the message. Else create the directory using the mkdir()method. Make the recursive call.
It means it will also recurse into subdirectories and add those files.
If you don't need to support Windows versions prior to Windows 2000, you can use the SHCreateDirectoryEx function for this. Consider this:
int createDirectoryRecursively( LPCTSTR path ) { return SHCreateDirectoryEx( NULL, path, NULL ); } // ... if ( createDirectoryRecursively( T("C:\\Foo\\Bar\\Baz") ) == ERROR_SUCCESS ) { // Bingo! }
In case using such shell32.dll API ever becomes an issue, you can always reimplement the createDirectoryRecursively function above with something else (possibly a hand-wired loop).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With