key_value2.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*!
  2. \file lib/gis/key_value2.c
  3. \brief Read/write Key_Value from/to file.
  4. (C) 2001-2008, 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 CERL
  8. */
  9. #include <grass/gis.h>
  10. /*!
  11. \brief Write key/value pairs to file
  12. \param[in,out] fd file to write to
  13. \param kv pointer Key_Value structure
  14. \return 0 success
  15. \return -1 error writing
  16. */
  17. int G_fwrite_key_value(FILE * fd, const struct Key_Value *kv)
  18. {
  19. int n;
  20. int err;
  21. err = 0;
  22. for (n = 0; n < kv->nitems; n++)
  23. if (kv->value[n][0]) {
  24. if (EOF == fprintf(fd, "%s: %s\n", kv->key[n], kv->value[n]))
  25. err = -1;
  26. }
  27. return err;
  28. }
  29. /*!
  30. \brief Read key/values pairs from file
  31. Allocated memory must be freed G_free_key_value().
  32. \param fd file to read key/values from
  33. \return pointer to allocated Key_Value structure
  34. \return NULL on error
  35. */
  36. struct Key_Value *G_fread_key_value(FILE * fd)
  37. {
  38. struct Key_Value *kv;
  39. char *key, *value;
  40. char buf[1024];
  41. kv = G_create_key_value();
  42. if (kv == NULL)
  43. return NULL;
  44. while (G_getl2(buf, sizeof(buf) - 1, fd) != 0) {
  45. key = value = buf;
  46. while (*value && *value != ':')
  47. value++;
  48. if (*value != ':')
  49. continue;
  50. *value++ = 0;
  51. G_strip(key);
  52. G_strip(value);
  53. G_set_key_value(key, value, kv);
  54. }
  55. return kv;
  56. }