Given these two blocks of code
fwrite(&x, sizeof(y), n, z);
And
for (int i = 0; i < n; i++)
{
fwrite(&x, sizeof(y), 1, z);
}
I was actually working on resize when my resized images were not written correctly using a piece of code similar to the first one!
I spent sometime banging my head against the wall until I decided to change the way I wrote to my outfile
and using a piece of code similar to the second one! Everything went well since then!
Per the manual page for fwrite()
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
The function
fwrite()
writesnmemb
elements of data, eachsize
bytes long, to the stream pointed to bystream
, obtaining them from the location given byptr
.
Is there really a difference between the first and the second pieces of code? If yes, what is it? If no, what could have possibly went wrong?
Edit: Here are the bytes of a doubly resized 3 x 3 bmp using the first and the second ways respectively
BMP 1:
0000036: 00ff00 00ff00 000000 702126 0900d0 72b7d4 000000 ff0000 .........p!&...r........
000004e: ff0000 000070 212609 00d072 b7d400 00ffff ff00ff 000000 .....p!&...r............
0000066: 007021 260900 d072b7 d40000 ffffff 00ff00 000000 702126 .p!&...r.............p!&
000007e: 0900d0 72b7d4 000000 ff0000 ff0000 000070 212609 00d072 ...r.............p!&...r
0000096: b7d400 0000ff 0000ff 000000 007021 260900 d072b7 d40000 .............p!&...r....
BMP 2:
0000036: 00ff00 00ff00 00ff00 00ff00 00ff00 00ff00 000000 ff0000 ........................
000004e: ff0000 ff0000 ff0000 ff0000 ff0000 0000ff 0000ff 00ffff ........................
0000066: ffffff ff00ff 0000ff 000000 00ff00 00ff00 ffffff ffffff ........................
000007e: 00ff00 00ff00 000000 ff0000 ff0000 ff0000 ff0000 ff0000 ........................
0000096: ff0000 0000ff 0000ff 0000ff 0000ff 0000ff 0000ff 000000 ........................