GRASS GIS 7 Programmer's Manual  7.9.dev(2021)-e5379bbd7
key_value2.c
Go to the documentation of this file.
1 /*!
2  \file lib/gis/key_value2.c
3 
4  \brief Read/write Key_Value from/to file.
5 
6  (C) 2001-2008, 2012 by the GRASS Development Team
7 
8  This program is free software under the GNU General Public License
9  (>=v2). Read the file COPYING that comes with GRASS for details.
10 
11  \author CERL
12  */
13 
14 #include <grass/gis.h>
15 
16 /*!
17  \brief Write key/value pairs to file
18 
19  \param[in,out] fd file to write to
20  \param kv pointer Key_Value structure
21 
22  \return 0 success
23  \return -1 error writing
24  */
25 int G_fwrite_key_value(FILE * fd, const struct Key_Value *kv)
26 {
27  int n;
28  int err;
29 
30  err = 0;
31  for (n = 0; n < kv->nitems; n++)
32  if (kv->value[n][0]) {
33  if (EOF == fprintf(fd, "%s: %s\n", kv->key[n], kv->value[n]))
34  err = -1;
35  }
36  return err;
37 }
38 
39 /*!
40  \brief Read key/values pairs from file
41 
42  Allocated memory must be freed G_free_key_value().
43 
44  \param fd file to read key/values from
45 
46  \return pointer to allocated Key_Value structure
47  \return NULL on error
48  */
49 struct Key_Value *G_fread_key_value(FILE * fd)
50 {
51  struct Key_Value *kv;
52  char *key, *value;
53  char buf[1024];
54 
55  kv = G_create_key_value();
56  if (kv == NULL)
57  return NULL;
58  while (G_getl2(buf, sizeof(buf) - 1, fd) != 0) {
59  key = value = buf;
60  while (*value && *value != ':')
61  value++;
62  if (*value != ':')
63  continue;
64  *value++ = 0;
65  G_strip(key);
66  G_strip(value);
67  G_set_key_value(key, value, kv);
68  }
69  return kv;
70 }
int G_getl2(char *, int, FILE *)
Gets a line of text from a file of any pedigree.
Definition: getl.c:64
struct Key_Value * G_fread_key_value(FILE *fd)
Read key/values pairs from file.
Definition: key_value2.c:49
void G_strip(char *)
Removes all leading and trailing white space from string.
Definition: strings.c:300
int G_fwrite_key_value(FILE *fd, const struct Key_Value *kv)
Write key/value pairs to file.
Definition: key_value2.c:25
#define NULL
Definition: ccmath.h:32
SYMBOL * err(FILE *fp, SYMBOL *s, char *msg)
Definition: symbol/read.c:220
char ** value
Definition: gis.h:506
void G_set_key_value(const char *, const char *, struct Key_Value *)
Set value for given key.
Definition: key_value1.c:38
char ** key
Definition: gis.h:505
Definition: gis.h:501
int nitems
Definition: gis.h:503
struct Key_Value * G_create_key_value(void)
Allocate and initialize Key_Value structure.
Definition: key_value1.c:23