Figure out what game data/objects need to be saved. Then
choose the method you want (FILE, ofstream, Windows HANDLE
functions, etc.). Then cycle through the data and write it to the
file. Then to load a game, just cycle through the file and read the
data back in.
Here are a few examples:
Say for instance that you need to save the game level (an int)
and the players name (a 10 element char array).
int Level;
char Name[10];
//using the FILE struct
Code:
//Save a game
FILE *fp=0;
fp=fopen("game.dat","wb");
fwrite((void *)&Level,sizeof(int),1,fp);
fwrite((void *)Name,sizeof(char),10,fp);
fflush(fp);
fclose(fp);
//Load a game
fp=fopen("game.data","rb");
fread((void *)&Level,sizeof(int),1,fp);
fread((void *)Name,sizeof(char),10,fp);
fclose(fp);
//using an ofstream
Code:
//Save a game
ofstream ofs;
ofs.open("game.dat",ios::binary);
ofs.write((char *)&Level,sizeof(int));
ofs.write((char *)Name,sizeof(char)*10);
ofs.flush();
ofs.close();
//Load a game
ifstream ifs;
ifs.open("game.dat",ios::binary);
ifs.read((char *)&Level,sizeof(int));
ifs.read((char *)Name,sizeof(char)*10);
ifs.close();
//using Windows HANDLEs
Code:
//Save the game
DWORD dw=0;
HANDLE hFile=0;
hFile=CreateFile("game.dat",GENERIC_WRITE,0,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
WriteFile(hFile,(void *)&Level,sizeof(int),&dw,0);
WriteFile(hFile,(void *)Name,sizeof(char)*10,&dw,0);
CloseHandle(hFile);
//Load the game
dw=0;
hFile=CreateFile("game.dat",GENERIC_READ,0,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
ReadFile(hFile,(void *)&Level,sizeof(int),&dw,0);
ReadFile(hFile,(void *)Name,sizeof(char)*10,&dw,0);
CloseHandle(hFile);
You'll have to include the appropriate header files (stdio.h for FILE and fstream for ofstream/ifstream).