-
Notifications
You must be signed in to change notification settings - Fork 111
/
toml_sample.c
60 lines (50 loc) · 1.22 KB
/
toml_sample.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
#include "toml.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void fatal(const char *msg, const char *msg1) {
fprintf(stderr, "ERROR: %s%s\n", msg, msg1 ? msg1 : "");
exit(1);
}
int main() {
FILE *fp;
char errbuf[200];
// 1. Read and parse toml file
fp = fopen("sample.toml", "r");
if (!fp) {
fatal("cannot open sample.toml - ", strerror(errno));
}
toml_table_t *conf = toml_parse_file(fp, errbuf, sizeof(errbuf));
fclose(fp);
if (!conf) {
fatal("cannot parse - ", errbuf);
}
// 2. Traverse to a table.
toml_table_t *server = toml_table_in(conf, "server");
if (!server) {
fatal("missing [server]", "");
}
// 3. Extract values
toml_datum_t host = toml_string_in(server, "host");
if (!host.ok) {
fatal("cannot read server.host", "");
}
toml_array_t *portarray = toml_array_in(server, "port");
if (!portarray) {
fatal("cannot read server.port", "");
}
printf("host: %s\n", host.u.s);
printf("port: ");
for (int i = 0;; i++) {
toml_datum_t port = toml_int_at(portarray, i);
if (!port.ok)
break;
printf("%d ", (int)port.u.i);
}
printf("\n");
// 4. Free memory
free(host.u.s);
toml_free(conf);
return 0;
}