key_value4.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*!
  2. \file key_value4.c
  3. \brief Key_Value management.
  4. (C) 2001-2008 by the GRASS Development Team
  5. This program is free software under the
  6. GNU General Public License (>=v2).
  7. Read the file COPYING that comes with GRASS
  8. for details.
  9. \author CERL
  10. */
  11. #include <grass/gis.h>
  12. #include <string.h>
  13. /*!
  14. \brief Update file, set up value for given key
  15. \param[in] file filename to be updated
  16. \param[in] key key value
  17. \param[in] value value to be updated
  18. \return -1 can't open file for reading
  19. \return -2 no memory for key,value info, file not modified
  20. \return -3 can't open file for re-write
  21. \return -4 error writing the file (might be damaged)
  22. */
  23. int G_update_key_value_file(const char *file, const char *key,
  24. const char *value)
  25. {
  26. struct Key_Value *kv;
  27. int stat;
  28. kv = G_read_key_value_file(file, &stat);
  29. if (stat != 0)
  30. return stat;
  31. if (!G_set_key_value(key, value, kv)) {
  32. G_free_key_value(kv);
  33. return -2;
  34. }
  35. G_write_key_value_file(file, kv, &stat);
  36. G_free_key_value(kv);
  37. return stat;
  38. }
  39. /*!
  40. \brief Look up for key in file
  41. \param[in] file filename
  42. \param[in] key key to be found in file
  43. \param[out] value value for key
  44. \param[in] n number of characters to be copied
  45. \return <0 are file/memory errors
  46. \return 0 not found
  47. \return 1 ok
  48. */
  49. int G_lookup_key_value_from_file(const char *file,
  50. const char *key, char value[], int n)
  51. {
  52. struct Key_Value *kv;
  53. int stat;
  54. const char *v;
  55. *value = 0;
  56. kv = G_read_key_value_file(file, &stat);
  57. if (stat != 0)
  58. return stat;
  59. v = G_find_key_value(key, kv);
  60. if (v) {
  61. strncpy(value, v, n);
  62. value[n - 1] = 0;
  63. stat = 1;
  64. }
  65. else
  66. stat = 0;
  67. G_free_key_value(kv);
  68. return stat;
  69. }