]> git.evergreen-ils.org Git - Evergreen.git/blob - OpenSRF/src/libjson/json_util.c
sort groups by name for consistancy
[Evergreen.git] / OpenSRF / 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 "json_util.h"
11 #include "json_tokener.h"
12 #include "bits.h"
13 #include "debug.h"
14 #include "printbuf.h"
15 #include "linkhash.h"
16 #include "arraylist.h"
17 #include "json_object.h"
18 #include "ossupport.h"
19 #include "json_object_private.h"
20
21
22
23 struct json_object* json_object_from_file(char *filename)
24 {
25   struct printbuf *pb;
26   struct json_object *obj;
27   char buf[JSON_FILE_BUF_SIZE];
28   int fd, ret;
29
30   if((fd = open(filename, O_RDONLY)) < 0) {
31     mc_error("json_object_from_file: error reading file %s: %s\n",
32              filename, strerror(errno));
33     return error_ptr(-1);
34   }
35   if(!(pb = printbuf_new())) {
36     mc_error("json_object_from_file: printbuf_new failed\n");
37     return error_ptr(-1);
38   }
39   while((ret = read(fd, buf, JSON_FILE_BUF_SIZE)) > 0) {
40     printbuf_memappend(pb, buf, ret);
41   }
42   close(fd);
43   if(ret < 0) {
44     mc_abort("json_object_from_file: error reading file %s: %s\n",
45              filename, strerror(errno));
46     printbuf_free(pb);
47     return error_ptr(-1);
48   }
49   obj = json_tokener_parse(pb->buf);
50   printbuf_free(pb);
51   return obj;
52 }
53
54 int json_object_to_file(char *filename, struct json_object *obj)
55 {
56   char *json_str;
57   int fd, ret, wpos, wsize;
58
59   if(!obj) {
60     mc_error("json_object_to_file: object is null\n");
61     return -1;
62   }
63
64   if((fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, 0644)) < 0) {
65     mc_error("json_object_to_file: error opening file %s: %s\n",
66              filename, strerror(errno));
67     return -1;
68   }
69   if(!(json_str = json_object_to_json_string(obj))) return -1;
70   wsize = strlen(json_str);
71   wpos = 0;
72   while(wpos < wsize) {
73     if((ret = write(fd, json_str + wpos, wsize-wpos)) < 0) {
74       close(fd);
75       mc_error("json_object_to_file: error writing file %s: %s\n",
76              filename, strerror(errno));
77       return -1;
78     }
79     wpos += ret;
80   }
81
82   close(fd);
83   return 0;
84 }