This commit is contained in:
CK Tan 2020-12-22 23:09:36 -08:00
parent 63feb40e3b
commit 94ded5f2c1

View file

@ -38,63 +38,62 @@ Below is an example of parsing the values from the example table.
#include <stdlib.h> #include <stdlib.h>
#include "toml.h" #include "toml.h"
static void fatal(const char* msg, const char* msg1) static void error(const char* msg, const char* msg1)
{ {
fprintf(stderr, "ERROR: %s%s\n", msg, msg1?msg1:""); fprintf(stderr, "ERROR: %s%s\n", msg, msg1?msg1:"");
exit(1); exit(1);
} }
int main() int main()
{ {
FILE* fp; FILE* fp;
char errbuf[200]; char errbuf[200];
// 1. Read and parse toml file // 1. Read and parse toml file
fp = fopen("sample.toml", "r"); fp = fopen("sample.toml", "r");
if (!fp) { if (!fp) {
fatal("cannot open sample.toml - ", strerror(errno)); error("cannot open sample.toml - ", strerror(errno));
} }
toml_table_t* conf = toml_parse_file(fp, errbuf, sizeof(errbuf)); toml_table_t* conf = toml_parse_file(fp, errbuf, sizeof(errbuf));
fclose(fp); fclose(fp);
if (!conf) { if (!conf) {
fatal("cannot parse - ", errbuf); error("cannot parse - ", errbuf);
} }
// 2. Traverse to a table. // 2. Traverse to a table.
toml_table_t* server = toml_table_in(conf, "server"); toml_table_t* server = toml_table_in(conf, "server");
if (!server) { if (!server) {
fatal("missing [server]", ""); error("missing [server]", "");
} }
// 3. Extract values // 3. Extract values
toml_datum_t host = toml_string_in(server, "host"); toml_datum_t host = toml_string_in(server, "host");
if (!host.ok) { if (!host.ok) {
fatal("cannot read server.host", ""); error("cannot read server.host", "");
} }
toml_array_t* portarray = toml_array_in(server, "port"); toml_array_t* portarray = toml_array_in(server, "port");
if (!portarray) { if (!portarray) {
fatal("cannot read server.port", ""); error("cannot read server.port", "");
} }
printf("host: %s\n", host.u.s); printf("host: %s\n", host.u.s);
printf("port: "); printf("port: ");
for (int i = 0; ; i++) { for (int i = 0; ; i++) {
toml_datum_t port = toml_int_at(portarray, i); toml_datum_t port = toml_int_at(portarray, i);
if (!port.ok) break; if (!port.ok) break;
printf("%d ", (int)port.u.i); printf("%d ", (int)port.u.i);
} }
printf("\n"); printf("\n");
// 4. Free memory // 4. Free memory
free(host.u.s); free(host.u.s);
toml_free(conf); toml_free(conf);
return 0; return 0;
} }
``` ```
#### Accessing Table Content #### Accessing Table Content