summaryrefslogtreecommitdiff
path: root/json_util.c
diff options
context:
space:
mode:
authorMichael Clark <michael@metaparadigm.com>2007-03-13 08:26:18 +0000
committerMichael Clark <michael@metaparadigm.com>2007-03-13 08:26:18 +0000
commitf0d08887b857fce1fe95a68d29eb7a07cd527d7c (patch)
treed4b37e182674cf62fb7671b0f6b033ff858aa1f5 /json_util.c
parent6d59966c4ef28fb4462f735c11f43ca93a62049f (diff)
import of version 0.1
git-svn-id: http://svn.metaparadigm.com/svn/json-c/trunk@2 327403b1-1117-474d-bef2-5cb71233fd97
Diffstat (limited to 'json_util.c')
-rw-r--r--json_util.c79
1 files changed, 79 insertions, 0 deletions
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 <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+
+#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;
+}