Max_P, (edited )
@Max_P@lemmy.max-p.me avatar

<span style="color:#323232;">    fp = fopen("data.json", "r");
</span><span style="color:#323232;">    fread(buffer, 1024, 1, fp);
</span><span style="color:#323232;">    fclose(fp);
</span>

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 feof 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:


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

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.

  • All
  • Subscribed
  • Moderated
  • Favorites
  • random
  • uselessserver093
  • Food
  • aaaaaaacccccccce
  • [email protected]
  • test
  • CafeMeta
  • testmag
  • MUD
  • RhythmGameZone
  • RSS
  • dabs
  • Socialism
  • KbinCafe
  • TheResearchGuardian
  • Ask_kbincafe
  • oklahoma
  • feritale
  • SuperSentai
  • KamenRider
  • All magazines