Whenever I write a struct
to a binary file, any struct
s after it go away, although any struct
s written before it remain.
I'm opening the file stream in binary output mode and my struct
s contain only primitive datatypes.
I also made sure to make separate file streams for each operation.
Output:
create players
765
51
save 1
765
save 2
765
51
** struct
definition**
struct player{
int UUID;
};
Function saving the struct
s
//updates player information in the player database
bool savePlayer(player playerData){
//count how manny playrs are in file
// Create our objects.
fstream countstream;
int count = 0;
countstream.open ("player.bin", ios::binary | ios::in);
if(countstream.is_open()){
countstream.seekg(0, ios::end); //set position to end
count = countstream.tellg()/sizeof(player);
//retuns number of players in file by getting
//the index of the position and dividing it by the size of each player
//no loops required :D
}
countstream.close();
bool found = false;
//if file is not empty,look through it
if(count > 0){
player playerTable[count];
fstream readstream;
readstream.open ("player.bin", ios::binary | ios::in);
//build table
for(int i = 0; i < count; i++){
readstream.seekg(i, ios::beg); //set position to end
readstream.read(reinterpret_cast <char *> (&playerTable[i]),
sizeof(player));
readstream.close();
}
//check table
for(int i = 0; i < count; i++){
if(playerTable[i].UUID == playerData.UUID){
found = true;
playerTable[i] = playerData;
}
}
//write table back to file
if(found){
fstream writestream; //create writestream
writestream.open ("player.bin", ios::binary | ios::out);
for(int i = 0; i < count; i++){
writestream.seekg(i, ios::beg); //set position to player
writestream.write(reinterpret_cast <char *> (&playerTable[i]),
sizeof(player));
if(!writestream.fail()){
writestream.close();
return true;
}
else{
writestream.close();
return false;
}
readstream.close();
}
}
}
//append if not found
if(!found){
fstream appendstream;
appendstream.open ("player.bin", ios::binary | ios::out |
ios::app);
appendstream.write(reinterpret_cast <char *> (&playerData),
sizeof(player));
appendstream.close();
if(!appendstream.fail()){
appendstream.close();
return true;
}
else{
appendstream.close();
return false;
}
}
return false;
}
Any suggestions will be appreciated.