X-Git-Url: https://pintos-os.org/cgi-bin/gitweb.cgi?a=blobdiff_plain;f=lib%2Fjson.c;h=3acaa1964d3d5b2fe66291819dc423bb36d0a210;hb=56244b81016f4d60082976845f296f98111d16a3;hp=6842c8baaf6b7f3d14b9f35c03f886473680620a;hpb=a105c27b4e24ac0d29ba131eca00793bc3385dca;p=openvswitch diff --git a/lib/json.c b/lib/json.c index 6842c8ba..3acaa196 100644 --- a/lib/json.c +++ b/lib/json.c @@ -1002,18 +1002,34 @@ json_from_string(const char *string) struct json * json_from_file(const char *file_name) { - struct json_parser *p; struct json *json; FILE *stream; - /* Open file. */ stream = fopen(file_name, "r"); if (!stream) { return json_string_create_nocopy( xasprintf("error opening \"%s\": %s", file_name, strerror(errno))); } + json = json_from_stream(stream); + fclose(stream); + + return json; +} + +/* Parses the contents of 'stream' as a JSON object or array, and returns a + * newly allocated 'struct json'. The caller must free the returned structure + * with json_destroy() when it is no longer needed. + * + * The file must be encoded in UTF-8. + * + * See json_from_string() for return value semantics. + */ +struct json * +json_from_stream(FILE *stream) +{ + struct json_parser *p; + struct json *json; - /* Read and parse file. */ p = json_parser_create(JSPF_TRAILER); for (;;) { char buffer[BUFSIZ]; @@ -1026,13 +1042,11 @@ json_from_file(const char *file_name) } json = json_parser_finish(p); - /* Close file and check for I/O errors. */ if (ferror(stream)) { json_destroy(json); json = json_string_create_nocopy( - xasprintf("error reading \"%s\": %s", file_name, strerror(errno))); + xasprintf("error reading JSON stream: %s", strerror(errno))); } - fclose(stream); return json; }