From 07c447e68a4a86697e5bcce9caeabc6c5f61cdbc Mon Sep 17 00:00:00 2001 From: Tristan Riehs Date: Sun, 3 May 2026 15:32:26 +0200 Subject: Try to handle blanks in config file --- src/uconfig.c | 61 +++++++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 40 insertions(+), 21 deletions(-) (limited to 'src') diff --git a/src/uconfig.c b/src/uconfig.c index 431f76a..ec06bd0 100644 --- a/src/uconfig.c +++ b/src/uconfig.c @@ -16,13 +16,13 @@ struct uconfig_s { struct uconfig_pair_s *tail; }; -static struct uconfig_pair_s *uconfig_pair_new(char *line, int sep_idx) +/* Create a new Uconfig pair. KEY and VALUE are copied to create the new + * pair. */ +static struct uconfig_pair_s *uconfig_pair_new(const char *key, const char *value) { - assert(line[sep_idx] == '='); - line[sep_idx] = '\0'; struct uconfig_pair_s *pair = malloc(sizeof(struct uconfig_pair_s)); - pair->key = strdup(line); - pair->value = strdup(line + sep_idx + 1); + pair->key = strdup(key); + pair->value = strdup(value); pair->next = NULL; return pair; } @@ -41,31 +41,50 @@ static void uconfig_add_tail(struct uconfig_s *uconfig, } } +static int char_is_blank(int c) +{ + return c == ' ' || c == '\t' || c == '\n'; +} + +/* Remove all the leading and trailing blank characters from STR. STR is + * modified in-place. */ +static char *trim(char *str) +{ + int len = strlen(str); + while ((len > 0) && char_is_blank(*str)) { + str++; + len--; + } + while ((len > 0) && char_is_blank(str[len - 1])) { + str[len - 1] = '\0'; + len--; + } + if (len == 0) { + fprintf(stderr, + "%s: warning: returning empty string\n", + __func__); + } + return str; +} + static int uconfig_parse_line(struct uconfig_s *uconfig, const char *file, int line_number, - char *line, - ssize_t line_len) + char *line) { - /* Remove trailing newline, if any */ - if (line[line_len - 1] == '\n') { - line[line_len - 1] = '\0'; - line_len--; - } - - /* Find index of '=' character in the line */ - int sep_idx = 0; - while ((sep_idx < line_len) && (line[sep_idx] != '=')) { - sep_idx++; - } - if (sep_idx == line_len) { + char *sep_ptr = strchr(line, '='); + if (sep_ptr == NULL) { fprintf(stderr, "%s: %s:%d: no '=' character found\n", __func__, file, line_number); return -1; } - struct uconfig_pair_s *pair = uconfig_pair_new(line, sep_idx); + *sep_ptr = '\0'; + char *key = trim(line); + char *value = trim(sep_ptr + 1); + + struct uconfig_pair_s *pair = uconfig_pair_new(key, value); uconfig_add_tail(uconfig, pair); return 0; } @@ -90,7 +109,7 @@ struct uconfig_s *uconfig_new(const char*file) line = malloc(line_size); while ((line_len = getline(&line, &line_size, input)) != -1) { - rc = uconfig_parse_line(uconfig, file, line_number, line, line_len); + rc = uconfig_parse_line(uconfig, file, line_number, line); if (rc == -1) goto err; line_number++; -- cgit v1.2.3