1    | /*
2    |  * Copyright (c) 2007-2014, Lloyd Hilaiel <me@lloyd.io>
3    |  *
4    |  * Permission to use, copy, modify, and/or distribute this software for any
5    |  * purpose with or without fee is hereby granted, provided that the above
6    |  * copyright notice and this permission notice appear in all copies.
7    |  *
8    |  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9    |  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10   |  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11   |  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12   |  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13   |  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14   |  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15   |  */
16   | 
17   | #include <stdio.h>
18   | #include <string.h>
19   | 
20   | #include "yajl/yajl_tree.h"
21   | 
22   | static unsigned char fileData[65536];
23   | 
24   | int
25   | main(void)
26   | {
27   |     size_t rd;
28   |     yajl_val node;
29   |     char errbuf[1024];
30   | 
31   |     /* NUL plug the buffers */
32   |     fileData[0] = '\0';
33   |     errbuf[0] = '\0';
34   | 
35   |     /* read the entire config file */
36   |     rd = fread((void *) fileData, (size_t) 1, sizeof(fileData) - 1, stdin);
37   | 
38   |     /* file read error handling */
39   |     if (rd == 0 && !feof(stdin)) {
40   |         fprintf(stderr, "error encountered on file read\n");
41   |         return 1;
42   |     } else if (rd >= sizeof(fileData) - 1) {
43   |         fprintf(stderr, "config file too big\n");
44   |         return 1;
45   |     }
46   | 
47   |     /* we have the whole config file in memory.  let's parse it ... */
48   |     node = yajl_tree_parse((const char *) fileData, errbuf, sizeof(errbuf));
49   | 
50   |     /* parse error handling */
51   |     if (node == NULL) {
52   |         fprintf(stderr, "parse_error: ");
53   |         if (strlen(errbuf)) {
54   |             fprintf(stderr, "%s", errbuf);
55   |         } else {
56   |             fprintf(stderr, "unknown error");
57   |         }
58   |         fprintf(stderr, "\n");
59   |         return 1;
60   |     }
61   | 
62   |     /* ... and extract a nested value from the config file */
63   |     {
64   |         const char * path[] = { "Logging", "timeFormat", (const char *) 0 };
65   | 
66   |         yajl_val v = yajl_tree_get(node, path, yajl_t_string);
67   | 
68   |         if (v) {
69   |             printf("%s/%s: %s\n", path[0], path[1], YAJL_GET_STRING(v));
70   |         } else {
71   |             printf("no such node: %s/%s\n", path[0], path[1]);
72   |         }
73   |     }
74   | 
75   |     yajl_tree_free(node);
76   | 
77   |     return 0;
78   | }