summaryrefslogtreecommitdiff
path: root/src/lib/file.c
blob: 693d0e54d7fc3d1ab4207d5c0013645f9785d05c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "mdb.h"

static char *getpair(int *c, FILE *fp);

// readdb - reads the given file into a key table list
// if fp returns NULL it will return the empty list
// if readdb fails it will return NULL
tablist_t *readdb(char *filename)
{
  int len = 2;
  tablist_t *list = calloc(len, sizeof(tablist_t));
  list[0].len = len;
  FILE *fp = fopen(filename, "rb");
  if (fp == NULL)
    return list;

  int c, i = 0, open = 0;
  char *p;
  while ((c = fgetc(fp)) != EOF) {
    switch (c) {
      case 250:
        p = getpair(&c, fp);
        if (p == NULL)
          return NULL;
        setkey(&list, i, p);
        free(p);
        break;
      case 251:
        if (open == 1)
          return NULL;
        open = 1;
        break;
      case 254:
        open = 0;
        i++;
        break;
      default:
        return NULL;
    }
  }
  fclose(fp);
  return list;
}

// writedb - writes a keytablist to a given file
void writedb(char *filename, tablist_t *list)
{
  FILE *fp = fopen(filename, "wb");
  for (int i = 0; i < list[0].len; ++i) {
    fprintf(fp, "\xfb");
    int *indexes = getkeys(list, i);
    for (int j = 0; indexes[j]; ++j) {
      fprintf(fp, "\xfa%s:", list[i].tab[indexes[j]].key);
      switch (list[i].tab[indexes[j]].flag) {
        case 1:
          fprintf(fp, "%.2lf\xfc", list[i].tab[indexes[j]].value.num);
          break;
        case 2:
          fprintf(fp, "%s\xfc", list[i].tab[indexes[j]].value.boolean ?
                  "true" : "false");
          break;
        case 3:
          fprintf(fp, "%s\xfc", list[i].tab[indexes[j]].value.str);
          break;
      }
    }
    free(indexes);
    fprintf(fp, "\xfe");
  }
  fclose(fp);
}

static char *getpair(int *c, FILE *fp)
{
  char *pair = calloc(3, sizeof(char));
  int i = 0, len = 3;
  while ((*c = fgetc(fp)) != 252 && *c != EOF) {
    if (i >= len)
      pair = realloc(pair, ++len * sizeof(char));
    pair[i++] = *c;
  }
  pair = realloc(pair, ++len * sizeof(char));
  pair[i] = '\0';
  if (*c != 252) {
    free(pair);
    return NULL;
  }
  return pair;
}