Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Trying to read/write structs to binary files...

Status
Not open for further replies.

supersumo

Programmer
Jul 16, 2003
2
US
I'm trying to use binary files to save my level data for a game. I had it working fine using text files, but I want to use binary files. The functions save the map array, but not the items or enemy array.
here is the kind of data I want to save:
int map[19][550];
ENEMY *enemy = new ENEMY[MAX_ENEMIES];
ITEM *item = new ITEM[MAX_ITEMS];

here are the functions to save/load:

int load_map(char *s) {
int old_max_items, old_max_enemies, i;
ifstream file_in(s, ios::in | ios::binary);
if (!file_in.is_open()) return 1;
file_in.read((char *)map, sizeof(map));
file_in.read((char *)enemy, sizeof(enemy));
file_in.read((char *)item, sizeof(item));
file_in.close();
return 0;
}

int save_map(char *s) {
ofstream file_out (s, ios::eek:ut | ios::binary | ios::trunc);
if (!file_out.is_open()) return 1;
file_out.write((char *)map, sizeof(map));
file_out.write((char *)enemy, sizeof(enemy));
file_out.write((char *)item, sizeof(item));
file_out.close();
return 0;
}

can anybody tell me why it wont save the enemy/item data, but it will save the map. Does it matter that enemy and item are pointers to struct and that map is a regular array?
 
>> Does it matter that enemy and item are pointers to
>> struct and that map is a regular array?

of course it does. sizeof() only knows that "enemy" and "item" are pointers not how many of them their are. Assuming that ENEMY and ITEM are data structures and not classes, you need to supply the actual size to the write() function:
Code:
file_out.write((char*)enemy, sizeof(enemy) * MAX_ENEMIES);

-pete
 
I've found the easiest method to read and write structures in "raw" mode is to use C-style input/output for files.

fread(&structname,sizeof(struct),1,file_in);

fwrite(&structname,sizeof(struct),1,file_out);

You can look these up for further information. Please note: if your struct has pointers to dynamic memory, you will have to handle re-designating the addresses pointed to the next application instance, since it will not be the same.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top