I have doubts about which order of the parameters size and count to use for fread/fwrite. If I want to read 8kb of data from file fp, which of the following is more efficient?
fread(data,1,8192,fp)
fread(data,8192,1,fp)
Also are there endiannes issues that I should be worried about?
They're not exactly equivalent.
fread()
was mis-designed. Its design ignores the possibilty of a partial read at the end of the file, which cannot be expressed by its return value, which is in units of the size you specified.You should really only use
fread()
where the size is 1 and the length is the number of bytes you're expecting. That's the only way you can properly deal with the situation. For types other thanchar
that means providingsizeof char
as the size andn*sizeof T
as the length, wheren
is the number ofT
s you are expecting.They're exactly equivalent. As for endianness, it depends on what you're reading. Normally, it will be a buffer of bytes, which you'll then have to "unformat", according to the format with which they were written. And since it's bytes, endianness plays no role.
EDIT:
As simonc pointed out (and then deleted, because he didn't get it 100% right---but his point was valid): there is a difference with regards to the return value (which you need to use in order to know whether the function worked or not).
fread( buffer, 8192, 1, fp )
will return either 0 or 1, and 1 only if all 8192 bytes have been read. In addition, Posix says that the contents of the buffer are not specified for partially read objects. In practice, the buffer will have been filled with as many bytes as could be read, but since you don't know how many that was, that doesn't buy you much. In sum, you should always usefread( buffer, 1, 8192, fp );
(since it makes no sense to use this function for anything but a buffer of bytes).