ca5ce7dc2542f1f7f8d8756dcdddf2bdd1a445cd
[oweals/busybox.git] / libbb / make_directory.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini make_directory implementation for busybox
4  *
5  * Copyright (C) 2001  Matt Kraai.
6  * 
7  * Rewriten in 2002
8  * Copyright (C) 2002 Glenn McGrath
9  * Copyright (C) 2002 Vladimir N. Oleynik
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  * General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24  *
25  */
26
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <sys/stat.h>
30 #include <sys/types.h>
31 #include <unistd.h>
32 #include <stdlib.h>
33
34 #include "libbb.h"
35
36 /* Create the directory PATH with mode MODE, or the default if MODE is -1.
37  * Also create parent directories as necessary if flags contains
38  * FILEUTILS_RECUR.  */
39
40 int make_directory (char *path, long mode, int flags)
41 {
42         int ret;
43
44         /* Calling apps probably should use 0777 instead of -1
45          * then we dont need this condition
46          */
47         if (mode == -1) {
48                 mode = 0777;
49         }
50         if (flags == FILEUTILS_RECUR) {
51                 char *pp = strrchr(path, '/');
52                 if (pp) {
53                         *pp = '\0';
54                         make_directory(path, mode, flags);
55                         *pp = '/';
56                 }
57         }
58         ret = mkdir(path, mode);
59         if ( (ret == -1) && (errno != EEXIST) ) {
60                 perror_msg("Cannot create directory %s", path);
61         }
62         return ret;
63 }