Code:
struct Data
{
string PlayerName;
unsigned int Health;
unsigned int Shields;
float Xpos;
float Ypos;
float Zpos;
};
bool SaveData(Data &data);
bool LoadData(Data &data);
Data player;
int _tmain(int argc, _TCHAR* argv[])
{
player.PlayerName = "Gordon";
player.Health = 100;
player.Shields = 100;
player.Xpos = 300;
player.Ypos = 100;
player.Zpos = 100;
if(SaveData(player))
{
cout << "Data Saved" << endl;
}
cout << "Would u like to load it back? " << endl;
char in;
cin >> in;
if(in =='y')
{
LoadData(player);
}
cout << "Size of: " << sizeof(Data) << endl;
while(1)
{}
return 0;
}
bool SaveData(Data &data)
{
char DataBuffer[256];
std::ofstream DataFile("Player.data");
DataFile.setf( ios_base::binary );
if(DataFile.is_open())
{
sprintf(DataBuffer,"Player Name: %s\n"
"Player Health: %d\n"
"Player Shields: %d\n"
"Player Position: \n"
"X: %.f\n"
"Y: %.f\n"
"Z: %.f\n",data.PlayerName.c_str(),data.Health,data.Shields,
data.Xpos,data.Ypos,data.Zpos);
DataFile.write((char*)&DataBuffer,sizeof(DataBuffer));
if(DataFile.is_open())
{
DataFile.close();
}
}
return true;
}
bool LoadData(Data &data)
{
char BufferData[256];
ifstream PlayerData("Player.data");
sprintf(BufferData,"Player Name: %s\n"
"Player Health: %d\n"
"Player Shields: %d\n"
"Player Position: \n"
"X: %.f\n"
"Y: %.f\n"
"Z: %.f\n",data.PlayerName.c_str(), data.Health,data.Shields,data.Xpos,
data.Ypos,
data.Zpos);
if(PlayerData.is_open())
{
PlayerData.read((char*)BufferData,sizeof(BufferData));
if(PlayerData.is_open())
{
PlayerData.close();
}
}
cout << "Player Name: " << data.PlayerName << endl;
cout << "Player Health: " << data.Health << endl;
cout << "Player Shileds: " << data.Shields << endl;
cout << "Player Position: " << endl;
cout << "X: " << data.Xpos << endl;
cout << "Y: " << data.Ypos << endl;
cout << "Z: " << data.Zpos << endl;
return true;
}
As you can see i used the write/read functions of the streams to write files now that seems to be better then using << but i could be wrong, are there any advantages to using write/read? or should i avoid them like the plague?