GRASS GIS 8 Programmer's Manual  8.2.2dev(2023)-3d2c704037
d_mkdir.c
Go to the documentation of this file.
1 /*!
2  * \file db/dbmi_driver/d_mkdir.c
3  *
4  * \brief DBMI Library (driver) - creare directories
5  *
6  * (C) 1999-2008 by the GRASS Development Team
7  *
8  * This program is free software under the GNU General Public
9  * License (>=v2). Read the file COPYING that comes with GRASS
10  * for details.
11  *
12  * \author Joel Jones (CERL/UIUC), Radim Blazek
13  */
14 
15 #include <string.h>
16 #include <unistd.h>
17 #include <sys/stat.h>
18 #include <sys/types.h>
19 #include <grass/dbmi.h>
20 #include "dbstubs.h"
21 
22 
23 static char *rfind(char *string, char c);
24 static int make_parent_dir(char *path, int mode);
25 static int make_dir(const char *path, int mode);
26 
27 
28 /*!
29  \brief Create db directory
30 
31  \param path full path
32  \param mode mode
33  \param parentdirs parent directories
34 
35  \return DB_OK on success
36  \return DB_FAILED on failure
37 */
38 int db_driver_mkdir(const char *path, int mode, int parentdirs)
39 {
40  if (parentdirs) {
41  char path2[GPATH_MAX];
42 
43  strcpy(path2, path);
44  if (make_parent_dir(path2, mode) != DB_OK)
45  return DB_FAILED;
46  }
47 
48  return make_dir(path, mode);
49 }
50 
51 
52 /* make a directory if it doesn't exist */
53 /* this routine could be made more intelligent as to why it failed */
54 static int make_dir(const char *path, int mode)
55 {
56  if (db_isdir(path) == DB_OK)
57  return DB_OK;
58 
59  if (G_mkdir(path) == 0)
60  return DB_OK;
61 
63 
64  return DB_FAILED;
65 }
66 
67 
68 static int make_parent_dir(char *path, int mode)
69 {
70  char *slash;
71  int stat;
72 
73  slash = rfind(path, '/');
74  if (slash == NULL || slash == path)
75  return DB_OK; /* no parent dir to make. return ok */
76 
77  *slash = 0; /* add NULL to terminate parentdir string */
78  if (access(path, 0) == 0) { /* path exists, good enough */
79  stat = DB_OK;
80  }
81  else if (make_parent_dir(path, mode) != DB_OK) {
82  stat = DB_FAILED;
83  }
84  else if (make_dir(path, mode) == DB_OK) {
85  stat = DB_OK;
86  }
87  else {
88  stat = DB_FAILED;
89  }
90  *slash = '/'; /* put the slash back into the path */
91 
92  return stat;
93 }
94 
95 
96 static char *rfind(char *string, char c)
97 {
98  char *found;
99 
100  found = NULL;
101  while (*string) {
102  if (*string == c)
103  found = string;
104  string++;
105  }
106 
107  return found;
108 }
int db_isdir(const char *)
Test if path is a directory.
Definition: isdir.c:29
void db_syserror(const char *)
Report system error.
#define NULL
Definition: ccmath.h:32
#define GPATH_MAX
Definition: gis.h:180
int db_driver_mkdir(const char *path, int mode, int parentdirs)
Create db directory.
Definition: d_mkdir.c:38
#define DB_FAILED
Definition: dbmi.h:72
Definition: path.h:16
int G_mkdir(const char *)
Creates a new directory.
Definition: paths.c:27
#define DB_OK
Definition: dbmi.h:71