From: Michael Heimpold Date: Mon, 21 Jul 2014 21:15:45 +0000 (+0200) Subject: Introduce json_object_from_fd X-Git-Tag: json-c-0.13-20171207~198^2 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=a7534dbb7e1405509a7efbf44033fd63e1dc8fc3;p=json-c Introduce json_object_from_fd Also refactor json_object_from_file to use json_object_from_fd internally. Signed-off-by: Michael Heimpold --- diff --git a/json_util.c b/json_util.c index 2a5621b..910d84c 100644 --- a/json_util.c +++ b/json_util.c @@ -64,30 +64,30 @@ static int sscanf_is_broken = 0; static int sscanf_is_broken_testdone = 0; static void sscanf_is_broken_test(void); -struct json_object* json_object_from_file(const char *filename) +/* + * Create a JSON object from already opened file descriptor. + * + * This function can be helpful, when you opened the file already, + * e.g. when you have a temp file. + * Note, that the fd must be readable at the actual position, i.e. + * use lseek(fd, 0, SEEK_SET) before. + */ +struct json_object* json_object_from_fd(int fd) { struct printbuf *pb; struct json_object *obj; char buf[JSON_FILE_BUF_SIZE]; - int fd, ret; + int ret; - if((fd = open(filename, O_RDONLY)) < 0) { - MC_ERROR("json_object_from_file: error opening file %s: %s\n", - filename, strerror(errno)); - return NULL; - } if(!(pb = printbuf_new())) { - close(fd); MC_ERROR("json_object_from_file: printbuf_new failed\n"); return NULL; } while((ret = read(fd, buf, JSON_FILE_BUF_SIZE)) > 0) { printbuf_memappend(pb, buf, ret); } - close(fd); if(ret < 0) { - MC_ERROR("json_object_from_file: error reading file %s: %s\n", - filename, strerror(errno)); + MC_ERROR("json_object_from_fd: error reading fd %d: %s\n", fd, strerror(errno)); printbuf_free(pb); return NULL; } @@ -96,6 +96,21 @@ struct json_object* json_object_from_file(const char *filename) return obj; } +struct json_object* json_object_from_file(const char *filename) +{ + struct json_object *obj; + int fd; + + if((fd = open(filename, O_RDONLY)) < 0) { + MC_ERROR("json_object_from_file: error opening file %s: %s\n", + filename, strerror(errno)); + return NULL; + } + obj = json_object_from_fd(fd); + close(fd); + return obj; +} + /* extended "format and write to file" function */ int json_object_to_file_ext(const char *filename, struct json_object *obj, int flags) diff --git a/json_util.h b/json_util.h index 387dbc4..f6fc52c 100644 --- a/json_util.h +++ b/json_util.h @@ -31,6 +31,7 @@ extern "C" { /* utility functions */ extern struct json_object* json_object_from_file(const char *filename); +extern struct json_object* json_object_from_fd(int fd); extern int json_object_to_file(const char *filename, struct json_object *obj); extern int json_object_to_file_ext(const char *filename, struct json_object *obj, int flags); extern int json_parse_int64(const char *buf, int64_t *retval);