toml/toml_sample.c

63 lines
1.2 KiB
C
Raw Normal View History

2020-11-02 02:31:50 +00:00
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include "toml.h"
2020-12-05 22:19:53 +00:00
static void fatal(const char* msg, const char* msg1)
{
fprintf(stderr, "ERROR: %s%s\n", msg, msg1?msg1:"");
exit(1);
}
int main()
2020-11-02 02:31:50 +00:00
{
FILE* fp;
char errbuf[200];
2020-12-05 22:19:53 +00:00
// 1. Read and parse toml file
2020-11-02 02:31:50 +00:00
fp = fopen("sample.toml", "r");
if (!fp) {
2020-12-05 22:19:53 +00:00
fatal("cannot open sample.toml - ", strerror(errno));
2020-11-02 02:31:50 +00:00
}
toml_table_t* conf = toml_parse_file(fp, errbuf, sizeof(errbuf));
fclose(fp);
if (!conf) {
2020-12-05 22:19:53 +00:00
fatal("cannot parse - ", errbuf);
2020-11-02 02:31:50 +00:00
}
2020-12-05 22:19:53 +00:00
// 2. Traverse to a table.
2020-11-02 02:31:50 +00:00
toml_table_t* server = toml_table_in(conf, "server");
if (!server) {
2020-12-05 22:19:53 +00:00
fatal("missing [server]", "");
2020-11-02 02:31:50 +00:00
}
2020-12-05 22:19:53 +00:00
// 3. Extract values
2020-11-02 18:07:33 +00:00
toml_datum_t host = toml_string_in(server, "host");
2020-11-02 02:31:50 +00:00
if (!host.ok) {
2020-12-05 22:19:53 +00:00
fatal("cannot read server.host", "");
2020-11-02 02:31:50 +00:00
}
2020-12-05 22:19:53 +00:00
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);
2020-11-02 02:31:50 +00:00
}
2020-12-05 22:19:53 +00:00
printf("\n");
2020-11-02 02:31:50 +00:00
2020-12-05 22:19:53 +00:00
// 4. Free memory
2020-11-02 02:31:50 +00:00
free(host.u.s);
toml_free(conf);
return 0;
}