key_value2.c 1.4 KB

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