Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> This doesn't work reliably because the arguments are wrong. It's "fread(buf, size_of_item, number_of_items, file_ptr)".

No it isn't. What C standard library are you using? Above code is correct in my C standard library ... man fread:

  SYNOPSIS
        #include <stdio.h>
        size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
        ....
        The function fread() reads nmemb items of data, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr.


How does the man page's "size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);" disagree with the GP's "fread(buf, size_of_item, number_of_items, file_ptr)"? Both seem to support that "fread(buf, N-1, 1, f);" is "telling it to read one item of size N-1".


Oh it doesn't. Sorry. Too early not enough sleep to be commenting ...


https://pubs.opengroup.org/onlinepubs/007904975/functions/fr...

"The fread() function shall read into the array pointed to by ptr up to nitems elements whose size is specified by size in bytes, from the stream pointed to by stream. For each object, size calls shall be made to the fgetc() function and the results stored, in the order read, in an array of unsigned char exactly overlaying the object. […] If a partial element is read, its value is unspecified."

It doesn't say you stop when fgetc() returns EOF (or an error), so by a strict reading the remainder of partial items is filled with fgetc()'s "EOF" return value. But the more relevant thing is that it says the value of a partial element is unspecified.

(Edited to point out the "unspecified" aspect.)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: