Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fread/fwrite size and count [duplicate]

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?

like image 662
danny Avatar asked Oct 16 '13 17:10

danny


2 Answers

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 use fread( buffer, 1, 8192, fp ); (since it makes no sense to use this function for anything but a buffer of bytes).

like image 195
James Kanze Avatar answered Nov 16 '22 16:11

James Kanze


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 than char that means providing sizeof char as the size and n*sizeof T as the length, where n is the number of Ts you are expecting.

like image 3
user207421 Avatar answered Nov 16 '22 17:11

user207421