I have a program that writes a constant struct to a binary file. I need it to be an exact match of another binary file that was created in a different manner. However, each time I run my executable, the resulting binary file is different. I need the produced file to be the same every time.
The code to reproduce the problem:
main.c:
#include <stdio.h>
typedef struct {
double vector1[3];
double vector2[3];
unsigned int a_uint32_field;
unsigned char a_uint8_field;
} Struct_type;
void CreateStruct(Struct_type* Struct_instance) {
Struct_instance->vector1[0] = 0.0;
Struct_instance->vector2[0] = 0.0;
Struct_instance->vector1[1] = 0.0;
Struct_instance->vector2[1] = 0.0;
Struct_instance->vector1[2] = 0.0;
Struct_instance->vector2[2] = 0.0;
Struct_instance->a_uint32_field = 0U;
Struct_instance->a_uint8_field = 0U;
}
int main() {
Struct_type Struct_instance;
FILE* file_pointer;
CreateStruct(&Struct_instance);
file_pointer = fopen("Saved_Struct.bin", "wb");
fwrite((void*)&Struct_instance, sizeof(Struct_instance), 1, file_pointer);
fclose(file_pointer);
return (0);
}
Compile with:
gcc -o executable main.c -m32 -O0
Then run:
./executable
The first time I've run it, the file ended with hexadecimal \AE\CB\FF, the second time it was \F4\9C\FF. Deleting the older file or letting it be erased by fopen seems to make no difference. It was supposed to end with all zeros, that is: 00\00\00
Why does this happen? How can I prevent it?