Comment on [HELP] Converting JSON to Sqlite in C

Max_P@lemmy.max-p.me ⁨1⁩ ⁨year⁩ ago

    fp = fopen("data.json", "r");
    fread(buffer, 1024, 1, fp);
    fclose(fp);

You’re only reading the first 1024 bytes, that document is much larger than 1024 bytes. So the JSON library gets an incomplete JSON that ends unexpectedly. You need a much larger buffer than 1024 (ideally dynamically allocated to the right size or expandable). fread can also fail or read less than the specified amount of bytes. The correct way to use fread is to keep calling it until it returns <1 and foef returns true, and adjust the pointer in buffer to advance by whatever fread returns since you can’t assume it will always return the full requested amount of data. If you have 256b of a file in memory and request to read 1024, it can return you the 256 immediately while it goes fetch the 768 others from disk. It usually doesn’t, but it can:

RETURN VALUE
       On success, the number of bytes read is returned (zero indicates end of
       file),  and the file position is advanced by this number.  It is not an
       error if this number is smaller than the  number  of  bytes  requested;
       this  may happen for example because fewer bytes are actually available
       right now (maybe because we were close to end-of-file,  or  because  we
       are reading from a pipe, or from a terminal), or because read() was in‐
       terrupted by a signal.  See also NOTES.

Read man 3 fread and man 2 read for more details, or look it up online.

Any particular reason it has to be C? That would be much much easier in Python or JS since you don’t have to worry about that kind of memory management. It’s a good learning experience though, C is useful to know even if you never use it, since everything ends up in libc.

source
Sort:hotnewtop