comparison libutil/dbread.c @ 27:ca8a6f95826a

implemented sws-card-lookup and underlying libutil functions
author Mychaela Falconia <falcon@freecalypso.org>
date Tue, 16 Mar 2021 23:22:37 +0000
parents
children fa81221ac9b6
comparison
equal deleted inserted replaced
26:322f6fcdc36e 27:ca8a6f95826a
1 /*
2 * This module implements functions for reading key=value database files.
3 */
4
5 #include <ctype.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <strings.h>
10 #include "dbread.h"
11
12 static
13 parse_read_line(dbs, filename_for_errs, lineno_for_errs)
14 struct dbread_state *dbs;
15 char *filename_for_errs;
16 int lineno_for_errs;
17 {
18 unsigned n;
19 char *cp, *np;
20
21 n = 0;
22 for (cp = dbs->linebuf; ; ) {
23 while (isspace(*cp))
24 cp++;
25 if (!*cp)
26 break;
27 if (*cp == '=') {
28 inv_syntax: fprintf(stderr, "%s line %d: invalid syntax\n",
29 filename_for_errs, lineno_for_errs);
30 return(-1);
31 }
32 for (np = cp; ; cp++) {
33 if (*cp == '=')
34 break;
35 if (!*cp || isspace(*cp))
36 goto inv_syntax;
37 }
38 *cp++ = '\0';
39 if (n >= DBREAD_MAX_KV_PAIRS) {
40 fprintf(stderr,
41 "%s line %d: too many key=value pairs\n",
42 filename_for_errs, lineno_for_errs);
43 return(-1);
44 }
45 dbs->kv_pairs[n].key = np;
46 dbs->kv_pairs[n].value = cp;
47 n++;
48 while (*cp && !isspace(*cp))
49 cp++;
50 if (*cp)
51 *cp++ = '\0';
52 }
53 dbs->num_kv_pairs = n;
54 return(0);
55 }
56
57 char *
58 dbread_find_key(dbs, sought_key)
59 struct dbread_state *dbs;
60 char *sought_key;
61 {
62 unsigned n;
63
64 for (n = 0; n < dbs->num_kv_pairs; n++)
65 if (!strcasecmp(dbs->kv_pairs[n].key, sought_key))
66 return dbs->kv_pairs[n].value;
67 return 0;
68 }
69
70 dbread_find_record(filename, dbs, sought_key, sought_value)
71 char *filename, *sought_key, *sought_value;
72 struct dbread_state *dbs;
73 {
74 FILE *inf;
75 int lineno;
76 char *cp;
77
78 inf = fopen(filename, "r");
79 if (!inf) {
80 perror(filename);
81 return(-1);
82 }
83 for (lineno = 1; fgets(dbs->linebuf, DBREAD_LINEBUF_SIZE, inf);
84 lineno++) {
85 if (!index(dbs->linebuf, '\n')) {
86 fprintf(stderr,
87 "%s line %d: too long or missing newline\n",
88 filename, lineno);
89 fclose(inf);
90 return(-1);
91 }
92 if (parse_read_line(dbs, filename, lineno) < 0) {
93 /* error msg already printed */
94 fclose(inf);
95 return(-1);
96 }
97 cp = dbread_find_key(dbs, sought_key);
98 if (!cp)
99 continue;
100 if (strcmp(cp, sought_value))
101 continue;
102 /* found our record: struct dbread_state is our return */
103 fclose(inf);
104 return(0);
105 }
106 fclose(inf);
107 fprintf(stderr, "error: %s=%s not found in %s\n", sought_key,
108 sought_value, filename);
109 return(-1);
110 }