-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsonv2.c
More file actions
71 lines (48 loc) · 1.31 KB
/
Copy pathjsonv2.c
File metadata and controls
71 lines (48 loc) · 1.31 KB
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
#include "jsonv2.h"
char* create_first_pair(char* key, char* value) {
int total_len = (strlen(key) + strlen(value) + 6);
char* kvp = malloc((strlen(key) + strlen(value) + 6) * sizeof(char));
sprintf(kvp, "\"%s\":\"%s\"", key, value);
kvp[total_len] = '\0';
return kvp;
}
void change_status(char** kvp, char new_status) {
if (*kvp == NULL) {
return;
}
(*kvp)[10] = new_status;
}
void add_kvp(char** kvp, char* key, char* value) {
int total_len = (strlen(key) + strlen(value) + 7);
*kvp = realloc(*kvp, (strlen(*kvp) + total_len) * sizeof(char));
char* temp = create_first_pair(key, value);
strcat(*kvp, ",");
strcat(*kvp, temp);
free(temp);
}
void destroy_kvps(char** kvp) {
if (*kvp != NULL) {
free(*kvp);
*kvp = NULL;
}
}
void write_to_file(char* kvp, char* filename) {
FILE* fp = fopen(filename, "w+");
if (fp == NULL) {
perror("Cannot open file");
return;
}
// print opening {
fprintf(fp, "{");
fprintf(fp, "%s", kvp);
fprintf(fp, "}");
fclose(fp);
}
// int main(int argc, char const *argv[])
// {
// char* kvp = create_first_pair("hello", "world");
// add_kvp(&kvp, "helloo", "again");
// write_to_file(kvp, "test.json");
// destroy_kvps(&kvp);
// return 0;
// }