mapset.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. /*!
  2. \file lib/gis/mapset.c
  3. \brief GIS library - environment routines (mapset)
  4. (C) 2001-2009, 2012 by the GRASS Development Team
  5. This program is free software under the GNU General Public License
  6. (>=v2). Read the file COPYING that comes with GRASS for details.
  7. \author Original author CERL
  8. */
  9. #include <string.h>
  10. #include <stdlib.h>
  11. #include <unistd.h>
  12. #include <grass/gis.h>
  13. #include <grass/glocale.h>
  14. #include "gis_local_proto.h"
  15. /*!
  16. \brief Get current mapset name
  17. Returns the name of the current mapset in the current location. This
  18. routine is often used when accessing files in the current
  19. mapset. See Mapsets for an explanation of mapsets.
  20. G_fatal_error() is called on error.
  21. \return mapset name
  22. */
  23. const char *G_mapset(void)
  24. {
  25. const char *m = G__mapset();
  26. if (!m)
  27. G_fatal_error(_("MAPSET is not set"));
  28. return m;
  29. }
  30. /*!
  31. \brief Get current mapset name (internal use only)
  32. See G_mapset().
  33. \return pointer mapset name
  34. \return NULL on error
  35. */
  36. const char *G__mapset(void)
  37. {
  38. return G_getenv_nofatal("MAPSET");
  39. }
  40. /*!
  41. \brief Get current mapset UNIX-like path
  42. Allocated buffer should be freed by G_free(). See
  43. G__mapset_path().
  44. Returns the full UNIX path name of the current mapset. For example,
  45. if the user is working in mapset <i>user1</i>, location
  46. <i>spearfish</i> in the <i>/home/user/grassdata</i> database
  47. directory, this routine will return a string which looks like
  48. <i>/home/user/grassdata/spearfish/user1</i>.
  49. This function also checks if mapset path is readable by the current
  50. user. It calls G_fatal_error() on failure.
  51. \return buffer with location path
  52. */
  53. char *G_mapset_path(void)
  54. {
  55. char *mapset;
  56. mapset = G__mapset_path();
  57. if (access(mapset, F_OK) != 0) {
  58. perror("access");
  59. G_fatal_error(_("MAPSET <%s> not available"), mapset);
  60. }
  61. return mapset;
  62. }
  63. /*!
  64. \brief Get current mapset UNIX-like path (internal use only)
  65. Allocated buffer should be freed by G_free(). See also
  66. G_mapset_path().
  67. \todo Support also Windows-like path (?)
  68. \return buffer with mapset path
  69. */
  70. char *G__mapset_path(void)
  71. {
  72. const char *mapset = G__mapset();
  73. const char *location = G_location();
  74. const char *base = G_gisdbase();
  75. char *mapset_path = G_malloc(strlen(base) + strlen(location) +
  76. strlen(mapset) + 3);
  77. sprintf(mapset_path, "%s/%s/%s", base, location, mapset);
  78. return mapset_path;
  79. }