Saving Classes/Structs
Posted:
Sun Jan 28, 2007 9:53 pm
by willg101
Is it possible in GE to save a class(or struct) to a .sav file?
For instance, if you had the code:
- Code: Select all
struct playerCodes
{
char playerName[50];
int state;
int type;
int level;
float health;
};
playerCodes strPlayerCodes[50];
Could I save this entire class to a file using the built in saveVars()? Or can you only save variables declared through the script editor menu?
Posted:
Mon Jan 29, 2007 12:23 am
by morcior
You can save whatever you like using the c file handling methods.
See fopen, fwrite, fread and fclose.
Heres some example code of how to load and save the player actors position. You can see how you can adapt it to save the variables in a struct, even an array of them.
- Code: Select all
int saveGame()
{
int i;
FILE *fil = fopen("save.gal", "wb"); // open file for binary write
if(!fil) return false;
// size_t fwrite(const void *buf, size_t size, size_t count, FILE *stream);
fwrite(&player.loc.x, sizeof(double), 1, fil);
fwrite(&player.loc.y, sizeof(double), 1, fil);
fclose(fil);
return 1;
}
int loadGame()
{
int tmp_i, i;
double tmp_d;
FILE *fil = fopen("save.gal", "rb"); // open for binary read
if(!fil || feof(fil)) { fclose(fil); return 0; }
// size_t fread(void *buf, size_t size, size_t count, FILE * stream);
fread(&tmp_d, sizeof(double), 1, fil); player.loc.x = tmp_d;
fread(&tmp_d, sizeof(double), 1, fil); player.loc.y = tmp_d;
fclose(fil);
}
Posted:
Mon Jan 29, 2007 12:32 am
by Game A Gogo
umm, for the two int, isn't it supose to be void?
Posted:
Mon Jan 29, 2007 2:27 am
by willg101
You mean for the function definition? or the parenthesis?
Functions can be any type (integer, float, double, long, void, etc) and in the parenthesis, you put the arguments. If there are none, you don't have to put anything in them.
Correct me here if I'm wrong, I'm still new to C\C++.
Posted:
Mon Jan 29, 2007 3:09 am
by morcior
You're right. The functions return int data type to indicated if the load/save operation was sucessful. 0=error, 1=ok!
That way in other code you can write:
- Code: Select all
if (loadgame())
// load sucessful
else
// load failed
By the way, the code is edited from another much longer piece of code I made and the load fucntion I posted is actually missing a return 1; at the end if you want it to work correctly!
Posted:
Mon Jan 29, 2007 8:52 pm
by willg101
Thank you very much, morcior!!