2 * $Id: json_util.c,v 1.4 2006/01/30 23:07:57 mclark Exp $
4 * Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
5 * Michael Clark <michael@metaparadigm.com>
7 * This library is free software; you can redistribute it and/or modify
8 * it under the terms of the MIT license. See COPYING for details.
22 #include <sys/types.h>
23 #endif /* HAVE_SYS_TYPES_H */
27 #endif /* HAVE_SYS_STAT_H */
31 #endif /* HAVE_FCNTL_H */
35 #endif /* HAVE_UNISTD_H */
38 # define WIN32_LEAN_AND_MEAN
41 #endif /* defined(WIN32) */
43 #if !HAVE_OPEN && defined(WIN32)
51 #include "json_object.h"
52 #include "json_tokener.h"
53 #include "json_util.h"
55 struct json_object* json_object_from_file(const char *filename)
58 struct json_object *obj;
59 char buf[JSON_FILE_BUF_SIZE];
62 if((fd = open(filename, O_RDONLY)) < 0) {
63 MC_ERROR("json_object_from_file: error reading file %s: %s\n",
64 filename, strerror(errno));
65 return (struct json_object*)error_ptr(-1);
67 if(!(pb = printbuf_new())) {
68 MC_ERROR("json_object_from_file: printbuf_new failed\n");
69 return (struct json_object*)error_ptr(-1);
71 while((ret = read(fd, buf, JSON_FILE_BUF_SIZE)) > 0) {
72 printbuf_memappend(pb, buf, ret);
76 MC_ABORT("json_object_from_file: error reading file %s: %s\n",
77 filename, strerror(errno));
79 return (struct json_object*)error_ptr(-1);
81 obj = json_tokener_parse(pb->buf);
86 int json_object_to_file(char *filename, struct json_object *obj)
90 unsigned int wpos, wsize;
93 MC_ERROR("json_object_to_file: object is null\n");
97 if((fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, 0644)) < 0) {
98 MC_ERROR("json_object_to_file: error opening file %s: %s\n",
99 filename, strerror(errno));
103 if(!(json_str = json_object_to_json_string(obj))) { return -1; }
106 wsize = (unsigned int)(strlen(json_str) & UINT_MAX); /* CAW: probably unnecessary, but the most 64bit safe */
108 while(wpos < wsize) {
109 if((ret = write(fd, json_str + wpos, wsize-wpos)) < 0) {
111 MC_ERROR("json_object_to_file: error writing file %s: %s\n",
112 filename, strerror(errno));
116 /* because of the above check for ret < 0, we can safely cast and add */
117 wpos += (unsigned int)ret;