Saving binary file into an array, data is being corrupted

I am working on this assignment, where for this part I am simply reading the file and saving it into a struct array. I am posting the main arguments of the array, and I will post the output. It seems to me that it is saving it and displaying it as binary, yet it should not be. I believe that there is a mistake in probably my "build array" function. Any help is appreciated





Source code:

//THE FOLLOWING IS THE REFRENCE TO BUILD ARRAY
//*********************************************

int buildArray( Player players[] )
{

Player onePlayer;
ifstream inputFile;
int i = 0;
int numPlayers;
inputFile.open( "binary_hockey", ios::binary );

if ( inputFile.fail() )
{
cout << "The binary_hockey input file did not open"; //failsafe to check file
exit(-1);
}

inputFile.read( (char *) &onePlayer, sizeof(Player) );

while ( inputFile )
{
onePlayer=players[i];

i++;
inputFile.read( (char *) &onePlayer, sizeof(Player) );
}
numPlayers = i-1;
inputFile.close();

}

//************************************************



void printArray( Player players[25], int numPlayers )
{
int i;
for (i=0; i<numPlayers ; i++)
{
cout << players[i].name << " " << players[i].goals << " " << players[i].assists << " " << players[i].rating <<"\n";

}
}




And the output looks as follows:


Chicago Blackhawks UNSORTED Report

Player Name | Goals | Assists | Rating | Points
------------------------------------------------------------------------------
7805616 0 0
1 66 2883586
0 7798784 33293898
╕√( -2 2006793411 2006793454
@♦ 4198400 1 2686250
? 1 0 2686216
╦♦πv►²( 0 2130378780 0
*²( 4728650 2686280 28
└iH 4720424 0 4269136
28 108 27
îjH 28 2686440 0
L╦G 4744432 2686440 4215228
¿²( 28 2686472 4224155
05@ 4708240 2686428 4215306
ɲ( 0 2686536 4744432
ädH 4748768 2686664 2
05@ 4708364 2686524 4225749
05@ 4744432 2686552 0
x♫¢ 0 1964962953 0
x♫¢ 0 1964962953 -1471895503
♦ -1 36 2686648
♦ 0 0 4705096
▄■( 8 1964970382 1964970338
σ⌐D¿ 2686704 2686744 2686916
╒î uæGs▌■   b◄▼u─[$u@‼@ 4199232 2686792 4199366

Chicago Blackhawks SORTED Report

Player Name | Goals | Assists | Rating | Points
------------------------------------------------------------------------------
Press Enter to return to Quincy...
should this thread be in general C++ programming?
Veszafein wrote:
inputFile.read( (char *) &onePlayer, sizeof(Player) );
Never do this. The only time this even has a chance of working is if the structure is POD. Most likely it is not.

The problem is that the structure is not represented in memory the same way it should be stored in a file. Can you post your structure definition?
Last edited on
L B, oddly enough, that is a required code given by the teacher for this assignment, I know its terrible coding, but I've caught many errors in her "given codes"

fg109, thanks!
Topic archived. No new replies allowed.