[Update 2016.03.17] Sorry for that I skipped the error checking for simplicity. I had check the errors, here is the complete code.
#define MAX_DATA 512
#define MAX_ROWS 100
typedef struct Database {
Address rows[MAX_ROWS];
int num; // Number of record in the DB.
} Database;
typedef struct Address {
int id;
int set;
char name[MAX_DATA];
char email[MAX_DATA];
} Address;
Database *db_ptr;
FILE *file;
int return_value;
// Write to file
db_ptr = (Database*)malloc(sizeof(Database));
if(!db_ptr) {
printf("Memory error!\n");
}
for(int i = 0; i < MAX_ROWS; i++) {
db_ptr->rows[i].id = i;
db_ptr->rows[i].set = 0;
}
char *filename = "test.db";
file = fopen(filename, "w");
if(!file) {
printf("Open(w) %s fail!\n", filename);
}
return_value = fwrite(db_ptr, sizeof(Database), 1, file);
printf("The return value from fwrite = %d\n", return_value);
free(db_ptr);
fclose(file);
// Read from file
db_ptr = (Database*)malloc(sizeof(Database));
if(!db_ptr) {
printf("Memory error!\n");
}
file = fopen(filename, "r+");
if(!file) {
printf("Open(r+) %s fail!\n", filename);
}
return_value = fread(db_ptr, sizeof(Database), 1, file);
printf("(1)The return value from fread = %d\n", return_value);
rewind(file);
return_value = fread(db_ptr, 1, sizeof(Database), file);
printf("(2)The return value from fread = %d\n", return_value);
printf("Sizeof(Database) = %lu\n", sizeof(Database));
free(db_ptr);
fclose(file);
The results are
"The return value from fwrite = 1"
"(1)The return value from fread = 1"
"(2)The return value from fread = 103204"
"Sizeof(Database) = 103204"
in Ubuntu15.04(64-bits) using gcc with -std=c99, and
"The return value from fwrite = 1"
"(1)The return value from fread = 0"
"(2)The return value from fread = 26832"
"Sizeof(Database) = 103204"
in Windows7(64-bits) using MinGW with -std=c99.
The size of the test.db are 103204 bytes in Ubuntu and 103205 bytes in Windows. It seems fail to read the whole structure of Database.
My question is that how this program has different behavior in different environment?