diff --git a/config_file.c b/config_file.c index a27e2e9e37..b489f7ba8f 100644 --- a/config_file.c +++ b/config_file.c @@ -18,7 +18,7 @@ struct config_file static char *getaline(FILE *file) { - char *newline = malloc(8); + char *newline = malloc(9); size_t cur_size = 8; size_t index = 0; @@ -28,12 +28,13 @@ static char *getaline(FILE *file) if (index == cur_size) { cur_size *= 2; - newline = realloc(newline, cur_size); + newline = realloc(newline, cur_size + 1); } newline[index++] = in; in = getc(file); } + newline[index] = '\0'; return newline; } @@ -48,7 +49,7 @@ static bool parse_line(struct entry_list *list, char *line) while (isspace(*line)) line++; - char *key = malloc(8); + char *key = malloc(9); size_t cur_size = 8; size_t index = 0; @@ -57,11 +58,12 @@ static bool parse_line(struct entry_list *list, char *line) if (index == cur_size) { cur_size *= 2; - key = realloc(key, cur_size); + key = realloc(key, cur_size + 1); } key[index++] = *line++; } + key[index] = '\0'; list->key = key; while (isspace(*line)) diff --git a/config_file.h b/config_file.h index 67e083e7db..8b0b0b71ba 100644 --- a/config_file.h +++ b/config_file.h @@ -6,13 +6,28 @@ typedef struct config_file config_file_t; +///// +// Config file format +// - # are treated as comments. Rest of the line is ignored. +// - Format is: key = value. There can be as many spaces as you like in-between. +// - Value can be wrapped inside "" for multiword strings. (foo = "hai u") + +// Loads a config file. Returns NULL if file doesn't exist. config_file_t *config_file_new(const char *path); +// Frees config file. void config_file_free(config_file_t *conf); +// All extract functions return true when value is valid and exists. Returns false otherwise. + +// Extracts a double from config file. bool config_get_double(config_file_t *conf, const char *entry, double *in); +// Extracts an int from config file. bool config_get_int(config_file_t *conf, const char *entry, int *in); +// Extracts a single char. If value consists of several chars, this is an error. bool config_get_char(config_file_t *conf, const char *entry, char *in); +// Extracts an allocated string in *in. This must be free()-d if this function succeeds. bool config_get_string(config_file_t *conf, const char *entry, char **in); +// Extracts a boolean from config. Valid boolean true are "true" and "1". Valid false are "false" and "0". Other values will be treated as an error. bool config_get_bool(config_file_t *conf, const char *entry, bool *in);