chiark / gitweb /
argument parsing and logging, etc.
[inn-innduct.git] / backends / map.c
1 /*  $Id: map.c 6135 2003-01-19 01:15:40Z rra $
2 **
3 */
4
5 #include "config.h"
6 #include "clibrary.h"
7 #include <errno.h>
8
9 #include "libinn.h"
10 #include "paths.h"
11
12 #include "map.h"
13
14
15 typedef struct _PAIR {
16     char        First;
17     char        *Key;
18     char        *Value;
19 } PAIR;
20
21 static PAIR     *MAPdata;
22 static PAIR     *MAPend;
23
24
25 /*
26 **  Free the map.
27 */
28 void
29 MAPfree(void)
30 {
31     PAIR        *mp;
32
33     for (mp = MAPdata; mp < MAPend; mp++) {
34         free(mp->Key);
35         free(mp->Value);
36     }
37     free(MAPdata);
38     MAPdata = NULL;
39 }
40
41
42 /*
43 **  Read the map file.
44 */
45 void
46 MAPread(const char *name)
47 {
48     FILE        *F;
49     int i;
50     PAIR        *mp;
51     char        *p;
52     char                buff[BUFSIZ];
53
54     if (MAPdata != NULL)
55         MAPfree();
56
57     /* Open file, count lines. */
58     if ((F = fopen(name, "r")) == NULL) {
59         fprintf(stderr, "Can't open %s, %s\n", name, strerror(errno));
60         exit(1);
61     }
62     for (i = 0; fgets(buff, sizeof buff, F) != NULL; i++)
63         continue;
64     mp = MAPdata = xmalloc((i + 1) * sizeof(PAIR));
65
66     /* Read each line; ignore blank and comment lines. */
67     fseeko(F, 0, SEEK_SET);
68     while (fgets(buff, sizeof buff, F) != NULL) {
69         if ((p = strchr(buff, '\n')) != NULL)
70             *p = '\0';
71         if (buff[0] == '\0'
72          || buff[0] == '#'
73          || (p = strchr(buff, ':')) == NULL)
74             continue;
75         *p++ = '\0';
76         mp->First = buff[0];
77         mp->Key = xstrdup(buff);
78         mp->Value = xstrdup(p);
79         mp++;
80     }
81     fclose(F);
82     MAPend = mp;
83 }
84
85
86 /*
87 **  Look up a name in the map, return original value if not found.
88 */
89 char *
90 MAPname(char *p)
91 {
92     PAIR        *mp;
93     char        c;
94
95     for (c = *p, mp = MAPdata; mp < MAPend; mp++)
96         if (c == mp->First && strcmp(p, mp->Key) == 0)
97             return mp->Value;
98     return p;
99 }