d_mkdir.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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. #include <string.h>
  15. #include <unistd.h>
  16. #include <sys/stat.h>
  17. #include <sys/types.h>
  18. #include <grass/dbmi.h>
  19. #include "dbstubs.h"
  20. static char *rfind(char *string, char c);
  21. static int make_parent_dir(char *path, int mode);
  22. static int make_dir(const char *path, int mode);
  23. /*!
  24. \brief Create db directory
  25. \param path full path
  26. \param mode mode
  27. \param parentdirs parent directories
  28. \return DB_OK on success
  29. \return DB_FAILED on failure
  30. */
  31. int db_driver_mkdir(const char *path, int mode, int parentdirs)
  32. {
  33. if (parentdirs) {
  34. char path2[GPATH_MAX];
  35. strcpy(path2, path);
  36. if (make_parent_dir(path2, mode) != DB_OK)
  37. return DB_FAILED;
  38. }
  39. return make_dir(path, mode);
  40. }
  41. /* make a directory if it doesn't exist */
  42. /* this routine could be made more intelligent as to why it failed */
  43. static int make_dir(const char *path, int mode)
  44. {
  45. if (db_isdir(path) == DB_OK)
  46. return DB_OK;
  47. if (G_mkdir(path) == 0)
  48. return DB_OK;
  49. db_syserror(path);
  50. return DB_FAILED;
  51. }
  52. static int make_parent_dir(char *path, int mode)
  53. {
  54. char *slash;
  55. int stat;
  56. slash = rfind(path, '/');
  57. if (slash == NULL || slash == path)
  58. return DB_OK; /* no parent dir to make. return ok */
  59. *slash = 0; /* add NULL to terminate parentdir string */
  60. if (access(path, 0) == 0) { /* path exists, good enough */
  61. stat = DB_OK;
  62. }
  63. else if (make_parent_dir(path, mode) != DB_OK) {
  64. stat = DB_FAILED;
  65. }
  66. else if (make_dir(path, mode) == DB_OK) {
  67. stat = DB_OK;
  68. }
  69. else {
  70. stat = DB_FAILED;
  71. }
  72. *slash = '/'; /* put the slash back into the path */
  73. return stat;
  74. }
  75. static char *rfind(char *string, char c)
  76. {
  77. char *found;
  78. found = NULL;
  79. while (*string) {
  80. if (*string == c)
  81. found = string;
  82. string++;
  83. }
  84. return found;
  85. }