add sample program

This commit is contained in:
CK Tan 2020-11-01 18:31:50 -08:00
parent 7a3e402cee
commit 3941e0bade
4 changed files with 60 additions and 1 deletions

1
.gitignore vendored
View file

@ -31,6 +31,7 @@
*.hex
toml_cat
toml_json
toml_sample
# Debug files
*.dSYM/

View file

@ -1,7 +1,7 @@
HFILES = toml.h
CFILES = toml.c
OBJ = $(CFILES:.c=.o)
EXEC = toml_json toml_cat
EXEC = toml_json toml_cat toml_sample
CFLAGS = -std=c99 -Wall -Wextra -fpic
LIB = libtoml.a
@ -30,6 +30,8 @@ toml_json: toml_json.c $(LIB)
toml_cat: toml_cat.c $(LIB)
toml_sample: toml_sample.c $(LIB)
tomlcpp.o: tomlcpp.cpp

3
sample.toml Normal file
View file

@ -0,0 +1,3 @@
[server]
host = "example.com"
port = 80

53
toml_sample.c Normal file
View file

@ -0,0 +1,53 @@
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include "toml.h"
toml_table_t* load()
{
FILE* fp;
char errbuf[200];
fp = fopen("sample.toml", "r");
if (!fp) {
fprintf(stderr, "ERROR: cannot open sample.toml - %s\n", strerror(errno));
exit(1);
}
toml_table_t* conf = toml_parse_file(fp, errbuf, sizeof(errbuf));
fclose(fp);
if (!conf) {
fprintf(stderr, "ERROR: cannot parse - %s\n", errbuf);
exit(1);
}
return conf;
}
int main()
{
toml_table_t* conf = load();
toml_table_t* server = toml_table_in(conf, "server");
if (!server) {
fprintf(stderr, "ERROR: missing [server]\n");
exit(1);
}
toml_access_t host = toml_string_in(server, "host");
if (!host.ok) {
fprintf(stderr, "ERROR: cannot read server.host.\n");
exit(1);
}
toml_access_t port = toml_int_in(server, "port");
if (!port.ok) {
fprintf(stderr, "ERROR: cannot read server.port.\n");
exit(1);
}
printf("host: %s, port %d\n", host.u.s, (int)port.u.i);
free(host.u.s);
toml_free(conf);
return 0;
}