Rick Noelle wrote:
Hi Joe and muser,
I may be wrong but I believe the fwrite line in your reply Joe should be:
fwrite(&myrecord, sizeof(long) , sizeof(myrecord), fp);
instead of:
fwrite(&myrecord, sizeof(myrecord), fp);
Best Regards,
Rick
1. Don't top-post. Replies are appended to the bottom of the reply
{like this one) or interspersed.
Sorry, my bad.
2. The format of the fwrite function:
#include <stdio.h>
size_t fwrite(void * pointer, /* pointer to data */
size_t element_size,
size_t count,
FILE * stream);
As taken from Section 15.13 in Harbison & Steele.
So according to your correction, you want to output
"sizeof(myrecord)" amount of "sizeof(long)" {element size}.
Which is confusing at best.
Sorry again, I had meant to indicate the array element count with the
second sizeof parameter and I indicated it incorrectly. Assuming the user
has a constant for the number of elements he could simply use that but
since I did not know the constant value I tried to use sizeof to derive
it. I should have written this:
fwrite(&myrecord, sizeof(long), (sizeof(myrecord)/sizeof(long)), fp);
or alternatively
fwrite(&myrecord, sizeof(long), (sizeof(myrecord)/sizeof myrecord.customer_code[0]), fp);
The way I understand the function, the first size indicates the size, in
bytes, of the chunks to be written, and the second size represents the
number of chunks to be written (the number of elements in the array).
sizeof(myrecord) will return the total bytes in the array and sizeof(long)
will return the number of bytes in a single element. By dividing the two,
we can derive the number of elements in the array.
Or if you want:
size_t bytes_written =
fwrite(&data, 1, sizeof(myrecord), fp);
The former is used to write many chunks, while the
latter writes many one-byte quantities.
This was the format I was after but I don't want to write one byte chunks,
I want to write chunks that are the same size as the individual
array elements. A long is one bytes (at least on my Linux box) so the one