Soo i'm a little confuse about the fread/fwrite function ...

from what i understood in the videos, you need 4 input for those to work, let's use fread for the exemple

fread("place to store the data", size, qty, filename)

i have trouble understanding the difference between the size and the quantity ... in pset4 recover we need to store 512 package of 8bits into an array from file which give fread(arr, sizeof(BYTE), 512, file) and my code worked like that but i read a little more on this forum and i found some other code where it was fread(arr, 512, sizeof(BYTE), file) or even fread(arr, 512, 1, file) i tested all the variant in my code and they all work ... so which is the proper way to write the fread function ??? and why the 3 variations work ?

thank you very much ... hopefully my question is more clear than my understanding of fread/fwrite

1 Answer 1


I was researching on this as well and found this page with a comprehensive answer here. sizeof(BYTE) is equivalent to 1 so the second and third "variations" are the same. Both first and second variations work in this case because the number of bytes in card.raw is exactly in multiples/blocks of 512.

If fread(arr, 512, sizeof(BYTE), file) was used AND the number of bytes was not in multiples of 512, the last few bytes short of 512 would not be read. You can see it as the code reading each 512 bytes as a 'block'; any fewer than 512 bytes will not be treated as a 'block' to be read.

On the other hand, fread(arr, sizeof(BYTE), 512, file) would have read all the remaining bytes short of 512. Which to use will depend on whether reading the remaining bytes that do not form a 'block' is useful to you.

  • Thanks !! the link is really helpfull ... i think what messed me up was the fact that the block were 512 so even if the wrong "semantic" is used it will still work !
    – MartinD
    Jun 9, 2020 at 17:54

You must log in to answer this question.

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