summaryrefslogtreecommitdiff
path: root/32_kvs/kv.c~
diff options
context:
space:
mode:
authorHaidong Ji2022-04-15 15:51:30 -0500
committerHaidong Ji2022-04-15 15:51:30 -0500
commit442a49ad5a48d417345959b903ae6a6d32d55759 (patch)
treec7127bb497e5e439018b1915e0136eec2c9cb124 /32_kvs/kv.c~
Great C programming funHEADmaster
Excellent fundamentals and displine training, many tools and techniques exercises: gdb, emacs, valgrind, git
Diffstat (limited to '32_kvs/kv.c~')
-rw-r--r--32_kvs/kv.c~81
1 files changed, 81 insertions, 0 deletions
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 <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+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;
+}