From 442a49ad5a48d417345959b903ae6a6d32d55759 Mon Sep 17 00:00:00 2001 From: Haidong Ji Date: Fri, 15 Apr 2022 15:51:30 -0500 Subject: Great C programming fun Excellent fundamentals and displine training, many tools and techniques exercises: gdb, emacs, valgrind, git --- 32_kvs/kv.c~ | 81 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 32_kvs/kv.c~ (limited to '32_kvs/kv.c~') diff --git a/32_kvs/kv.c~ b/32_kvs/kv.c~ new file mode 100644 index 0000000..d215207 --- /dev/null +++ b/32_kvs/kv.c~ @@ -0,0 +1,81 @@ +#include "kv.h" +#include +#include +#include + +char *splitLine2KV(char *line, const char *delim) { + char *v = strstr(line, delim); + + if (v == NULL) + return NULL; + + *v = '\0'; + return v + strlen(delim); +} + +kvarray_t *readKVs(const char *fname) { + FILE *f = fopen(fname, "r"); + if (f == NULL) { + fprintf(stderr, "Could not open file\n"); + return NULL; + } + + kvarray_t *kvArray = malloc(sizeof(*kvArray)); + kvArray->kvarray = NULL; + char *line = NULL; + size_t sz = 0; + int i = 0; + + while (getline(&line, &sz, f) >= 0) { + char *v; + v = splitLine2KV(line, "="); + if (v) { + char *value = malloc((strlen(v) + 1) * sizeof(*value)); + strcpy(value, strtok(v, "\n")); + char *key = malloc((strlen(line) + 1) * sizeof(*key)); + strcpy(key, line); + + kvpair_t *kvPair = malloc(sizeof(kvPair)); + kvPair->key = key; + kvPair->value = value; + kvArray->kvarray = realloc(kvArray->kvarray, (i + 1) * sizeof(kvpair_t)); + kvArray->kvarray[i] = *kvPair; + free(kvPair); + i++; + kvArray->kvarrayLength = i; + } + } + free(line); + + if (fclose(f) != 0) { + fprintf(stderr, "Could not close file\n"); + return NULL; + } + + return kvArray; +} + +void freeKVs(kvarray_t *pairs) { + for (int i = 0; i < pairs->kvarrayLength; i++) { + free(pairs->kvarray[i].key); + free(pairs->kvarray[i].value); + } + free(pairs->kvarray); + free(pairs); +} + +void printKVs(kvarray_t *pairs) { + for (int i = 0; i < pairs->kvarrayLength; i++) { + printf("key = '%s' value = '%s'\n", pairs->kvarray[i].key, + pairs->kvarray[i].value); + } +} + +char *lookupValue(kvarray_t *pairs, const char *key) { + for (int i = 0; i < pairs->kvarrayLength; i++) { + if (strcmp(pairs->kvarray[i].key, key) == 0) { + return pairs->kvarray[i].value; + } + } + return NULL; +} -- cgit v1.2.3