On Mon, Nov 26, 2018 at 9:45 PM Andy A <
andy0...@gmail.com> wrote:
>
> I apologize for the multiple posts.
>
> This is the code I'm experimenting with. There are 3 objects in the file. The values from only one object are being printed:
>
...
> size_t result = fread (buffer, 1, f_size, fp);
First problem: you're only calling fread once, and with a size that
could be larger than BUF_SIZE.
If your file happens to be small enough to fit in BUF_SIZE, then
you're probably ok, but this won't work in general.
For larger inputs you'll need to loop on reading no more than BUF_SIZE
bytes into the buffer, then incrementally feeding that to the json
tokener.
> json_object *new_object = json_tokener_parse_ex (tok, buffer, f_size);
Problem 2: you're passing the full file size here, not however actual
bytes fread() read. (i.e. result)
> json_object_object_foreach (new_object, key, val)
Problem 3: you're assuming parse_ex actually returned an object. If
it hasn't yet parsed a complete object then it will return NULL and
this foreach will crash.
> ...
> while ((jerr = json_tokener_get_error (tok)) == json_tokener_continue);
Problem 4: if you've parsed a complete object, get_error will indicate
json_tokener_success instead, but actually you need to check for both
values.
If you get NULL and json_tokener_continue, read more bytes from the
file and call parse_ex again.
If you get non-NULL and json_tokener_success, do whatever you need to
with the returned object, then adjust your offset into your buffer and
the bytes available and pass the remaining bytes into parse_ex to
start the next object.
> do
> {
> tok = json_tokener_new_ex (JSON_TOKENER_DEFAULT_DEPTH);
> ...
> while (...)
Problem 5: you're leaking tokener objects each time you go through this loop.
In brief, you need to adjust how you're calling
json_tokener_parse_ex() so you keep giving it more bytes to parse the
next object by using tok->char_offset and arranging to re-fill your
buffer as needed.
Eric