24
|
1 #include <stdio.h>
|
|
2 #include <stdlib.h>
|
|
3 #include <unistd.h>
|
|
4 #include <ctype.h>
|
|
5 #include <string.h>
|
|
6
|
|
7 #include "list.h"
|
|
8
|
|
9 #define MAX_LENGHT_INPUT 1024
|
|
10 #define cfg_entry(n) list_entry(n, cfg_entry_t, list)
|
|
11
|
|
12 typedef struct _cfg_entry_t {
|
|
13 char *key;
|
|
14 char *value;
|
|
15 struct list_head list;
|
|
16 } cfg_entry_t;
|
|
17
|
|
18 static LIST_HEAD(cfg_list);
|
|
19
|
|
20
|
|
21 void push_in_list(char *key, char *value)
|
|
22 {
|
|
23 cfg_entry_t *new_entry = calloc(1, sizeof(cfg_entry_t));
|
|
24
|
|
25 new_entry->key = (char *) calloc(1, strlen(key) + 1);
|
|
26 new_entry->value = (char *) calloc(1, strlen(value) + 1);
|
|
27
|
|
28 strcpy(new_entry->key, key);
|
|
29 strcpy(new_entry->value, value);
|
|
30
|
|
31 list_add(&new_entry->list, &cfg_list);
|
|
32 }
|
|
33
|
|
34 int cfg_file(char *filename)
|
|
35 {
|
|
36 FILE *fp;
|
|
37 char *buf;
|
|
38 char *line;
|
|
39 char *value;
|
|
40
|
|
41 buf = malloc(255);
|
|
42
|
|
43 if ((fp = fopen(filename, "r")) == NULL) {
|
|
44 perror("fopen (parsecfg.c:46)");
|
|
45 exit(EXIT_FAILURE);
|
|
46 }
|
|
47
|
|
48 while (fgets(buf, 255, fp) != NULL) {
|
|
49 line = buf;
|
|
50
|
|
51 while (isspace((int) *line))
|
|
52 line++;
|
|
53
|
|
54 while ((strlen(line) > 0)
|
|
55 && isspace((int) line[strlen(line) - 1]))
|
|
56 line[strlen(line) - 1] = '\0';
|
|
57
|
|
58 if ((*line == '\n') || (*line == '\0') || (*line == '#'))
|
|
59 continue;
|
|
60
|
|
61 if ((strchr(line, '=') != NULL)) {
|
|
62 value = strchr(line, '=');
|
|
63 *value = '\0';
|
|
64 value++;
|
|
65
|
|
66 while (isspace((int) *value))
|
|
67 value++;
|
|
68
|
|
69 while ((strlen(line) > 0)
|
|
70 && isspace((int) line[strlen(line) - 1]))
|
|
71 line[strlen(line) - 1] = '\0';
|
|
72
|
|
73 push_in_list(line, value);
|
|
74 continue;
|
|
75 }
|
|
76 fprintf(stderr, "CFG: orphaned line \"%s\"\n", line);
|
|
77 }
|
|
78 return 1;
|
|
79 }
|
|
80
|
|
81 char *cfg_read(char *key)
|
|
82 {
|
|
83 struct list_head *n, *pos;
|
|
84 cfg_entry_t *search_entry = NULL;
|
|
85
|
|
86 list_for_each_safe(pos, n, &cfg_list) {
|
|
87 search_entry = cfg_entry(pos);
|
|
88 if (search_entry->key) {
|
|
89 if (!strcasecmp(search_entry->key, key)) {
|
|
90 return search_entry->value;
|
|
91 }
|
|
92 }
|
|
93 }
|
|
94 return NULL;
|
|
95 }
|