i have seen many examples where people uses fwrite with the qty value = 1, and this happens most of the times. However, i would like to have better clarity on the below 2 concepts. I have tried on code and they are apparently different. But why so?

for (int k=0; k<n; k++)
   fwrite(&a, sizeof(whatever), 1, outptr);


fwrite(&a, sizeof(whatever), n, outptr);


fwrite(&a, n*sizeof(whatever), 1, outptr);

The for loop will write n copies of the data stored at a to the file.

The single fwrite will write n*sizeof(whatever) bytes starting at the address of a. If does NOT write n copies of a.

The former is the way to write multiple copies of one item, the latter is the way to write n consecutive items from memory.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

  • Hi can i then ask the difference between "fwrite(&a, sizeof(whatever), n, outptr);" and "fwrite(&a, n*sizeof(whatever), 1, outptr); " ? – Yan Bo Pei May 26 '18 at 6:50
  • A good followup question. The second parameter specifies the size of each element to be written. The third parameter specifies how many consecutive elements to write. It doesn't say how many copies of one element to write. The difference is that the first version writes n consecutive elements, while the second version writes only one element. – Cliff B May 26 '18 at 7:11
  • As another example, consider these. fwrite( foo, 512, 1, outptr), would write a single 512 byte "element" out to the file, while fwrite( foo, 1, 512, outptr) would write out 512 elements of 1 byte each (like maybe chars). Finally, fwrite( foo, 20, 6, outptr) would write out 6 consecutive elements that are 20 bytes each. – Cliff B May 26 '18 at 7:11
  • oops, I just noticed the n*sizeof() in your example! My bad. However, that means that your examples correspond exactly to my 512,1 vs. 1,512 examples. Sorry about that. ;-) – Cliff B May 26 '18 at 7:20
  • Hi could you give a more detailed example on what exactly would be differently written for the between fwrite( foo, 1, 512, outptr) and fwrite( foo, 512, 1, outptr)? – Yan Bo Pei May 26 '18 at 8:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .