I have adapted a program that implements a register of players and stores the players in a struct, with BIN file handling. Now it's not possible to use the records after they have been loaded from the BIN file. The compile is ok and both functions below are excuted without crash but when one of the struct variables are read after the BIN file has been input, then the program will crash (segmentation fault).
I'm not sure any more that this will be possible to implement file handling like this with an array of struct due to that each record will have a variable size (variable size of the strings). The examples I have seen and tested works when each player is defined like this:
Player player1;
Player player2;
This is the code that does not work.:
const int SIZE = 200;
struct Player
{
string name;
int age;
int goals;
string team;
};
Player player[SIZE];
int main()
{
/* input of players in main both at start of the program from file and with cin
number of players are stored in numberOfplayers
the function output to file is called from here when the program is terminated
*/
}
int WriteToFile(string FILENAME, const Player player[], int numberOfPlayers)
{
ofstream ofile;
ofile.open(FILENAME.c_str(), ios::out | ios::binary);
if(!ofile)
{
cout << "Not possible to open the file" << endl;
return 1;
}
ofile.seekp(0);
for (int i =0; i < numberOfPlayers; i++)
{
ofile.write((char *)&player[i], sizeof(Player) );
}
ofile.close();
}
int ReadFromFile(string FILENAME, Player player[])
{
ifstream ifile;
long numrecs;
ifile.open(FILENAME.c_str(), ios::in | ios::binary);
if (!ifile)
{
cout << "Not possible to open the file" << endl;
return 0;
}
ifile.seekg(0L, ios::end); // go to end of file
numrecs = ifile.tellg() / sizeof(Player);
ifile.seekg(0L, ios::beg); // go to start of file
for (int i = 0; i < numrecs; i++)
{
ifile.read((char *)&player[i], sizeof(Player) );
}
ifile.close();
return numrecs;
}