I want an easy way to create multiple directories in C++/Linux.
For example I want to save a file lola.file in the directory:
/tmp/a/b/c
but if the directories are not there I want them to be created automagically. A working example would be perfect.
The others got you the right answer, but I thought I'd demonstrate another neat thing you can do:
Will create the following paths:
The braces allow you to create multiple directories at once on the same level of the hierarchy, whereas the
-p
option means "create parent directories as needed".Here's a C function that can be compiled with C++ compilers.
The macros
STRDUP()
andFREE()
are error-checking versions ofstrdup()
andfree()
, declared inemalloc.h
(and implemented inemalloc.c
andestrdup.c
). The"sysstat.h"
header deals with broken versions of<sys/stat.h>
and can be replaced by<sys/stat.h>
on modern Unix systems (but there were many issues back in 1990). And"jlss.h"
declaresmkpath()
.The change between v1.12 (previous) and v1.13 (above) is the test for
EEXIST
indo_mkdir()
. This was pointed out as necessary by Switch — thank you, Switch. The test code has been upgraded and reproduced the problem on a MacBook Pro (2.3GHz Intel Core i7, running Mac OS X 10.7.4), and suggests that the problem is fixed in the revision (but testing can only show the presence of bugs, never their absence).(You are hereby given permission to use this code for any purpose with attribution.)