-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.c
98 lines (81 loc) · 2.06 KB
/
utils.c
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
94
95
96
97
98
#include "utils.h"
char* slurp_file(const char* filename)
{
FILE* f = fopen(filename, "rb");
if (!f)
{
printf("Error opening file %s\n", filename);
exit(1);
}
fseek(f, 0, SEEK_END);
long f_len = ftell(f);
if (f_len < 9)
{
printf("Json file empty\n");
exit(1);
}
fseek(f, 0, SEEK_SET);
char* data = malloc(f_len+1);
fread(data, 1, f_len, f);
data[f_len] = '\0';
fclose(f);
return data;
}
void read_json(char** json_raw, char**** json, uint16_t* n_fields)
{
*n_fields = 0;
char c;
uint32_t i = 1;
while ((c = (*json_raw)[i]) != '\0')
{
if ((*json_raw)[i] == '\n' && (*json_raw)[i-1] != '{' && (*json_raw)[i-1] != '}' && (*json_raw)[i-1] != '\n')
(*n_fields)++;
i++;
}
(*json) = malloc((*n_fields) * sizeof(char**));
i = 0;
uint32_t left = 0, json_idx = 0;
uint8_t kv = 0;
while ((c = (*json_raw)[i]) != '\0')
{
if (c == '"')
{
if (left == 0)
left = i+1;
else
{
if (!kv) (*json)[json_idx] = malloc(2 * sizeof(char*));
(*json)[json_idx][kv] = malloc(1 + i - left);
for (uint16_t j = left; j < i; j++)
(*json)[json_idx][kv][j-left] = (*json_raw)[j];
(*json)[json_idx][kv][i - left] = '\0';
left = 0;
if (kv) json_idx++;
kv = (kv+1)%2;
}
}
i++;
}
}
void free_json(char*** json, uint16_t n_fields, char* json_raw)
{
for (uint16_t i = 0; i < n_fields; i++)
{
free(json[i][0]);
free(json[i][1]);
free(json[i]);
}
free(json);
if (json_raw) free(json_raw);
}
// int main(int argc, char* argv[])
// {
// char*** json = NULL;
// uint16_t n_fields = 0;
// read_json_file("config.json", &json, &n_fields);
// for (uint16_t j = 0; j < n_fields; j++)
// {
// printf("%s :: %s\n", json[j][0], json[j][1]);
// }
// return 0;
// }