Config_ini
This commit is contained in:
parent
cfb2aaabef
commit
2e1261f695
6 changed files with 140 additions and 0 deletions
80
config_ini/conf.c
Normal file
80
config_ini/conf.c
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
#include "conf.h"
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX_LINE 256
|
||||
#define MAX_VAL 128
|
||||
|
||||
/* Trim leading/trailing whitespace */
|
||||
static char *trim(char *str) {
|
||||
char *end;
|
||||
|
||||
while (isspace((unsigned char)*str)) str++;
|
||||
if (*str == 0)
|
||||
return str; // only spaces
|
||||
|
||||
end = str + strnlen(str, MAX_VAL) - 1;
|
||||
|
||||
while (end > str && isspace((unsigned char)*end)) end--;
|
||||
end[1] = '\0';
|
||||
return str;
|
||||
}
|
||||
|
||||
/* Load INI-style config */
|
||||
Config *config_load(const char *filename) {
|
||||
FILE *f = fopen(filename, "r");
|
||||
if (!f)
|
||||
return NULL;
|
||||
|
||||
Config *cfg = calloc(1, sizeof(Config));
|
||||
char line[MAX_LINE];
|
||||
|
||||
while (fgets(line, sizeof(line), f)) {
|
||||
char *s = trim(line);
|
||||
|
||||
// Skip empty or comment lines
|
||||
if (*s == '\0' || *s == '#' || *s == ';')
|
||||
continue;
|
||||
|
||||
char *eq = strchr(s, '=');
|
||||
if (!eq)
|
||||
continue; // invalid line, skip
|
||||
|
||||
*eq = '\0';
|
||||
char *key = trim(s);
|
||||
char *val = trim(eq + 1);
|
||||
|
||||
ConfigEntry *entry = malloc(sizeof(ConfigEntry));
|
||||
entry->key = strndup(key, MAX_VAL);
|
||||
entry->value = strndup(val, MAX_VAL);
|
||||
entry->next = cfg->head;
|
||||
cfg->head = entry;
|
||||
}
|
||||
|
||||
fclose(f);
|
||||
return cfg;
|
||||
}
|
||||
|
||||
/* Get value for a key */
|
||||
const char *config_get(Config *cfg, const char *key) {
|
||||
for (ConfigEntry *e = cfg->head; e; e = e->next) {
|
||||
if (strncmp(e->key, key, MAX_VAL) == 0)
|
||||
return e->value;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* Free the config struct */
|
||||
void config_free(Config *cfg) {
|
||||
ConfigEntry *e = cfg->head;
|
||||
while (e) {
|
||||
ConfigEntry *next = e->next;
|
||||
free(e->key);
|
||||
free(e->value);
|
||||
free(e);
|
||||
e = next;
|
||||
}
|
||||
free(cfg);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue