Ben Pfaff wrote:
Quote:
David Mathog <mathog@caltech.eduwrites:
Quote:
When reading a binary input stream with fread() one can
read N bytes in two ways :
count=fread(buffer,1,N,fin); /* N bytes at a time */
or
count=fread(buffer,N,1,fin); /* 1 buffer at a time */
I would assume the latter form would be faster, or at least
less of a load on the CPU. That's just an assumption though,
is it typically true?
>
No. Typically fread will multiply the second and third arguments
together and read (at least) that many bytes. The two forms are
then equivalent.
There's still a significant difference in the return value.
Particularly on
end of file. There's also a subtle difference in the contents of the
buffer
on partial read.
But the reason that the parameters are typically multiplied is because
of the standard...
The fread function reads, into the array pointed to by ptr, up to
nmemb
elements whose size is specified by size, from the stream pointed to
by stream. For each object, size calls are 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 indeterminate.
So, fread must work even if the buffer is not suitably aligned for an
object of the given size. Beacuse of that, plus the fact that I/O to
disc
itself is typically _much_ slower than any post I/O processing, and
standard I/O functions are synchronous, most implementations won't
bother looking for very minor performance improvement transferring
object size (2nd parameter) chunks.
Aside: Note that fread is typically used on binary streams.
Unfortunately, the standard still allows for binary streams to have
trailing null bytes. That means that using fread to read an unknown
number of objects can fail, because fread can return a count that
isn't actually correct.
So, when using fread/fwrite, it can make life slightly easier for file
formats include a true count of the number of objects being read
before the objects themselves are stored. In which case, unless
there is a particular need to detect partially read objects, you may
as well use the 'sizeof *p,N' form.
--
Peter