fwrite/fread problems (binary I/O)

Status
Not open for further replies.

dodexahedron

Ars Praefectus
3,368
Subscriptor++
I have a typedef as follows:

Code:
typedef double foo[2];

I do the following to create an array of foo:

Code:
foo* bar = (foo*)malloc(sizeof(foo) * arraySize);

I fill the values of bar with random values in the first position and zero in the second position as follows:
Code:
for(unsigned int i = 0; i < arraySize; i++)
{
  bar[i][0] = randomFunctionReturningDouble();
  bar[i][1] = 0;
}

Then, later on, I want to write the array to disk in binary form, so I do:

Code:
FILE* outputFile = fopen("file.bin","w");
fwrite(bar, sizeof(foo) * arraySize, 1, outputFile);
fclose(outputFile);

However, when I later read the file back in, as follows:
Code:
foo* bar = (foo*)malloc(sizeof(foo) * arraySize);
FILE* inputFile = fopen("file.bin","w");
fread(bar, sizeof(foo) * arraySize, 1, inputFile);
fclose(inputFile);
I end up with a different array.

I've tried using
Code:
fwrite(bar, sizeof(foo), arraySize, outputFile);
but the results are the same (identical, but wrong).

What am I missing?
 
Status
Not open for further replies.