First thing you need to do is check the return values from fopen, fwrite, fread, fseek, etc. You will start seeing errors that you are missing.
One thing you need to understand is that fseek will not seek past the end-of-file. Thus, if you are starting with an empty file and fwrite 40 bytes, then fseek to 512, then fwrite another 40 bytes, the second write will actually start at byte 80, not 512! You then fseek to 512, ending up at EOF at 80 and try to fread 40 bytes. You will actually read 0 bytes as you are at EOF and your read buffer will contain whatever it had previously (uninitialized memory?).