fread/fwrite size and count [duplicate]

2020-04-07 04:16发布

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?

2条回答
来,给爷笑一个
2楼-- · 2020-04-07 05:01

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.

查看更多
家丑人穷心不美
3楼-- · 2020-04-07 05:03

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).

查看更多
登录 后发表回答