I have a structure with all the data for a contestant. I have a function where I input the value of contestants' data like team name, team hometown, team foundation date and etc. Then I have a function to write that data to a binary file and also a function to read that data from the binary file.
My structure:
struct Team {
string teamName;
string teamHometown;
int foundedDay{};
int foundedMonth{};
int foundedYear{};
int matchPlayed{};
int matchLost{};
int goalsFor{};
int goalsAgainst{};
int goalDifference{};
int Points{};
};
My write and read functions:
void writeBinary(Team* T, int& contestantCount) {
Team Data;
ofstream File;
File.open("Data.bin", ios::binary | ios::out);
if (File.is_open()) {
File.write(reinterpret_cast<char*>(&Data), sizeof(Team));
File.close();
system("cls");
cout << "|--------------------------------------------------------------------------------------------|" << endl;
cout << " DATA SUCCESSFULLY SAVED TO BINARY FILE" << endl;
cout << "|--------------------------------------------------------------------------------------------|" << endl << endl;
system("pause");
}
else {
system("cls");
cout << "|--------------------------------------------------------------------------------------------|" << endl;
cout << " COULD NOT OPEN BINARY DATA FILE" << endl;
cout << "|--------------------------------------------------------------------------------------------|" << endl << endl;
system("pause");
}
}
void readBinary(Team* T, int& contestantCount) {
Team Data;
ifstream File;
File.open("Data.bin", ios::binary | ios::in);
if (File.is_open()) {
File.read(reinterpret_cast<char*>(&Data), sizeof(Team));
File.close();
system("cls");
cout << "|--------------------------------------------------------------------------------------------|" << endl;
cout << " SHOWING SAVED DATA FROM BINARY FILE" << endl;
cout << "|--------------------------------------------------------------------------------------------|" << endl << endl;
}
else {
system("cls");
cout << "|--------------------------------------------------------------------------------------------|" << endl;
cout << " COULD NOT OPEN BINARY DATA FILE" << endl;
cout << "|--------------------------------------------------------------------------------------------|" << endl << endl;
system("pause");
}
cout << Data.teamName << endl;
system("pause");
}
I assume that my write function works fine since it doesn't give me any violations in the code and I can see that the .bin
file is created with the contents in it. When I run the read function though, it gives me this violation and it gives me "Read access violation" in the terminal.
Here is a picture of the result in the console when I run the read function and a picture of the violation that it gives me after the function reaches its end.