Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive mkdir() system call on Unix

Tags:

c

unix

posix

mkdir

After reading the mkdir(2) man page for the Unix system call with that name, it appears that the call doesn't create intermediate directories in a path, only the last directory in the path. Is there any way (or other function) to create all the directories in the path without resorting to manually parsing my directory string and individually creating each directory ?

like image 436
Alex Marshall Avatar asked Feb 25 '10 17:02

Alex Marshall


People also ask

How do you create a recursive directory in Unix?

The -p option is used to create multiple child directories with mkdir command in a recursive manner. In order to create directories recursively non of the specified directories should exist because all of them are created automatically. In the following example, we create the directories aaa , bbb and ccc .

Is mkdir a system call?

mkdir() - Unix, Linux System Call.

What is the recursive command in Linux?

The recursive option with the cp command allows you to easily duplicate a directory.


2 Answers

There is not a system call to do it for you, unfortunately. I'm guessing that's because there isn't a way to have really well-defined semantics for what should happen in error cases. Should it leave the directories that have already been created? Delete them? What if the deletions fail? And so on...

It is pretty easy to roll your own, however, and a quick google for 'recursive mkdir' turned up a number of solutions. Here's one that was near the top:

http://nion.modprobe.de/blog/archives/357-Recursive-directory-creation.html

static void _mkdir(const char *dir) {     char tmp[256];     char *p = NULL;     size_t len;      snprintf(tmp, sizeof(tmp),"%s",dir);     len = strlen(tmp);     if (tmp[len - 1] == '/')         tmp[len - 1] = 0;     for (p = tmp + 1; *p; p++)         if (*p == '/') {             *p = 0;             mkdir(tmp, S_IRWXU);             *p = '/';         }     mkdir(tmp, S_IRWXU); } 
like image 69
Carl Norum Avatar answered Oct 04 '22 11:10

Carl Norum


hmm I thought that mkdir -p does that?

mkdir -p this/is/a/full/path/of/stuff

like image 38
j03m Avatar answered Oct 04 '22 11:10

j03m