]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/libjson/json_util.c
LGPL'd json C library. Slightly modified to build a .so file so we can link
[OpenSRF.git] / src / libjson / json_util.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <errno.h>
5 #include <unistd.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <fcntl.h>
9
10 #include "bits.h"
11 #include "debug.h"
12 #include "printbuf.h"
13 #include "json_object.h"
14 #include "json_tokener.h"
15 #include "json_util.h"
16
17
18 struct json_object* json_object_from_file(char *filename)
19 {
20   struct printbuf *pb;
21   struct json_object *obj;
22   char buf[JSON_FILE_BUF_SIZE];
23   int fd, ret;
24
25   if((fd = open(filename, O_RDONLY)) < 0) {
26     mc_error("json_object_from_file: error reading file %s: %s\n",
27              filename, strerror(errno));
28     return error_ptr(-1);
29   }
30   if(!(pb = printbuf_new())) {
31     mc_error("json_object_from_file: printbuf_new failed\n");
32     return error_ptr(-1);
33   }
34   while((ret = read(fd, buf, JSON_FILE_BUF_SIZE)) > 0) {
35     printbuf_memappend(pb, buf, ret);
36   }
37   close(fd);
38   if(ret < 0) {
39     mc_abort("json_object_from_file: error reading file %s: %s\n",
40              filename, strerror(errno));
41     printbuf_free(pb);
42     return error_ptr(-1);
43   }
44   obj = json_tokener_parse(pb->buf);
45   printbuf_free(pb);
46   return obj;
47 }
48
49 int json_object_to_file(char *filename, struct json_object *obj)
50 {
51   char *json_str;
52   int fd, ret, wpos, wsize;
53
54   if(!obj) {
55     mc_error("json_object_to_file: object is null\n");
56     return -1;
57   }
58
59   if((fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, 0644)) < 0) {
60     mc_error("json_object_to_file: error opening file %s: %s\n",
61              filename, strerror(errno));
62     return -1;
63   }
64   if(!(json_str = json_object_to_json_string(obj))) return -1;
65   wsize = strlen(json_str);
66   wpos = 0;
67   while(wpos < wsize) {
68     if((ret = write(fd, json_str + wpos, wsize-wpos)) < 0) {
69       close(fd);
70       mc_error("json_object_to_file: error writing file %s: %s\n",
71              filename, strerror(errno));
72       return -1;
73     }
74     wpos += ret;
75   }
76
77   close(fd);
78   return 0;
79 }