The fwrite function is writing row by row starting at the end of the array. Think of the array as the image mirrored vertically. (Left-right is maintained but top-bottom is reversed.) I'm sorry for confusing you by saying byte-by-byte earlier.
Here's the declaration for fwrite
size_t fwrite(const void *ptr, size_t size, size_t nitems,
We are using size=4, and nitems=pitch (the width in pixels of the iamge), so each fwrite is writing 4*pitch bytes. The fwrite function returns the number of items (not bytes) which should be equal to pitch in our case. The array's memory address begins at file->pixels, so at the beginning of the loop to write the last row from the array the offset would be (pitch*(ysz-1)). The next to last row would begin at (pitch*(ysz-2)).
HTH and sorry for not having the concentration earlier.