I'm writing a function that gets a binary file with integers and reverses their order. For example, I have this binary file (in hexadecimal):
00 00 00 01 00 00 00 02 00 00 00 03 00 00 00 04
and I want it to be:
00 00 00 04 00 00 00 03 00 00 00 02 00 00 00 01
But with my algorithm I get this:
00 00 00 01 00 00 00 02 00 00 00 03 00 00 00 04 CC CC CC CC 00 00 00 00 CC CC CC CC
And I don't get why... This is my algorithm:
void reverse(FILE * fr)
{
int i, num1, num2, fileLength;
fseek(fr, 0, SEEK_END);
fileLength = ftell(fr) / sizeof(int);
for(i = 0; i < fileLength / 2; i++)
{
fseek(fr, i * sizeof(int), SEEK_SET);
fread(&num1, sizeof(int), 1, fr);
fseek(fr, i * sizeof(int), SEEK_END);
fread(&num2, 4, 1, fr);
fseek(fr, i * sizeof(int), SEEK_END);
fwrite(&num2, sizeof(int), 1, fr);
fseek(fr, i * sizeof(int), SEEK_SET);
fwrite(&num1, sizeof(int), 1, fr);
}
}
int main()
{
FILE * f = fopen("test.bin", "r+b");
reverse(f);
fclose(f);
getchar();
return 0;
}
What am I doing wrong?
EDIT: I am given a file size that divides by sizeof(int).
EDIT 2:
After changing the code as pts pointed out, it still doesn't work. it outputs:
CC CC CC CC CC CC CC CC 00 00 00 03 00 00 00 04 00 00 00 01 00 00 00 00 00 00 00 02
my edited code is shown above.
(By the way, to all the commenters, I was told not to read the whole file to memory and then reverse it because it's supposed to be an excercise in file manipulation, not in memory manipulation.)
Thanks.