From f0d08887b857fce1fe95a68d29eb7a07cd527d7c Mon Sep 17 00:00:00 2001 From: Michael Clark Date: Tue, 13 Mar 2007 08:26:18 +0000 Subject: import of version 0.1 git-svn-id: http://svn.metaparadigm.com/svn/json-c/trunk@2 327403b1-1117-474d-bef2-5cb71233fd97 --- json_util.c | 79 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 json_util.c (limited to 'json_util.c') diff --git a/json_util.c b/json_util.c new file mode 100644 index 0000000..483644e --- /dev/null +++ b/json_util.c @@ -0,0 +1,79 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "bits.h" +#include "debug.h" +#include "printbuf.h" +#include "json_object.h" +#include "json_tokener.h" +#include "json_util.h" + + +struct json_object* json_object_from_file(char *filename) +{ + struct printbuf *pb; + struct json_object *obj; + char buf[JSON_FILE_BUF_SIZE]; + int fd, ret; + + if((fd = open(filename, O_RDONLY)) < 0) { + mc_error("json_object_from_file: error reading file %s: %s\n", + filename, strerror(errno)); + return error_ptr(-1); + } + if(!(pb = printbuf_new())) { + mc_error("json_object_from_file: printbuf_new failed\n"); + return error_ptr(-1); + } + while((ret = read(fd, buf, JSON_FILE_BUF_SIZE)) > 0) { + printbuf_memappend(pb, buf, ret); + } + close(fd); + if(ret < 0) { + mc_abort("json_object_from_file: error reading file %s: %s\n", + filename, strerror(errno)); + printbuf_free(pb); + return error_ptr(-1); + } + obj = json_tokener_parse(pb->buf); + printbuf_free(pb); + return obj; +} + +int json_object_to_file(char *filename, struct json_object *obj) +{ + char *json_str; + int fd, ret, wpos, wsize; + + if(!obj) { + mc_error("json_object_to_file: object is null\n"); + return -1; + } + + if((fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, 0644)) < 0) { + mc_error("json_object_to_file: error opening file %s: %s\n", + filename, strerror(errno)); + return -1; + } + if(!(json_str = json_object_to_json_string(obj))) return -1; + wsize = strlen(json_str); + wpos = 0; + while(wpos < wsize) { + if((ret = write(fd, json_str + wpos, wsize-wpos)) < 0) { + close(fd); + mc_error("json_object_to_file: error writing file %s: %s\n", + filename, strerror(errno)); + return -1; + } + wpos += ret; + } + + close(fd); + return 0; +} -- cgit v1.2.1