Debian Codegraph @

tests/xdot2json.c

raw
1 // utility for translating xdot to JSON via the xdot API
2
3 #include <errno.h>
4 #include <graphviz/xdot.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8
9 int main(int argc, char **argv) {
10
11 if (argc > 3 || (argc > 1 && strcmp(argv[1], "--help") == 0)) {
12 fprintf(stderr, "usage: %s [input_file [output_file]]\n", argv[0]);
13 return EXIT_FAILURE;
14 }
15
16 // setup input source
17 FILE *input = stdin;
18 if (argc > 1) {
19 input = fopen(argv[1], "r");
20 if (input == NULL) {
21 fprintf(stderr, "failed to open %s: %s", argv[1], strerror(errno));
22 return EXIT_FAILURE;
23 }
24 }
25
26 // there is no API for parsing from a file handle, so read the entire file
27 // into a string buffer
28 char *in = NULL;
29 size_t off = 0;
30 size_t sz = 0;
31 do {
32 char buf[BUFSIZ];
33 size_t r = fread(buf, 1, sizeof(buf), input);
34 if (r == 0) {
35 if (ferror(input)) {
36 fprintf(stderr, "failed while reading %s\n", argv[1]);
37 free(in);
38 fclose(input);
39 return EXIT_FAILURE;
40 }
41 } else {
42 // do we need to expand our buffer?
43 if (sz < r || sz - r < off) {
44 size_t s = sz == 0 ? BUFSIZ : 2 * sz;
45 char *i = realloc(in, s);
46 if (i == NULL) {
47 fprintf(stderr, "out of memory\n");
48 free(in);
49 fclose(input);
50 return EXIT_FAILURE;
51 }
52 in = i;
53 sz = s;
54 }
55 memcpy(in + off, buf, r);
56 off += r;
57 }
58 } while (!feof(input));
59
60 // we no longer need the input file
61 fclose(input);
62
63 // NUL-terminate the read input
64 if (off == sz) {
65 char *i = realloc(in, sz + 1);
66 if (i == NULL) {
67 fprintf(stderr, "out of memory\n");
68 free(in);
69 return EXIT_FAILURE;
70 }
71 in = i;
72 ++sz;
73 }
74 in[off] = '\0';
75
76 // parse input into an xdot object
77 xdot *x = parseXDot(in);
78 free(in);
79 if (x == NULL) {
80 fprintf(stderr, "failed to parse input into xdot\n");
81 return EXIT_FAILURE;
82 }
83
84 // setup output sink
85 FILE *output = stdout;
86 if (argc > 2) {
87 output = fopen(argv[2], "w");
88 if (output == NULL) {
89 fprintf(stderr, "failed to open %s: %s", argv[2], strerror(errno));
90 freeXDot(x);
91 return EXIT_FAILURE;
92 }
93 }
94
95 // turn that into JSON
96 jsonXDot(output, x);
97
98 // clean up
99 freeXDot(x);
100 fclose(output);
101
102 return EXIT_SUCCESS;
103 }