This is why I hate File I/O

Started by
11 comments, last by Ekim_Gram 18 years, 10 months ago
Quote:Original post by Ekim_Gram
I'm still a little confused to what you're saying. Why would I want to append to the file? It'll just get gradually larger and larger every time I write to it, which is why I set it to just over write.


Ok right now this is what is happening:

You have this code:
for (int i=1; i<11; i++){	High_Scores[i-1].Rank = i;	High_Scores[i-1].Score = 0;	WriteHighScoreToFile(High_Scores[i-1]);}

Everytime WriteHighScoreToFile is called, which is declared as this:
bool WriteHighScoreToFile(SHigh_Score High_Score){	std::ofstream fout;	fout.open("highscores.dat",std::ios::binary);	if (fout == NULL)		return 1;	fout.write((char*)(&High_Score), sizeof(SHigh_Score));	fout.close();	return 0;}

The line fout.open("highscores.dat",std::ios::binary); opens up the "highscores.dat" file and overwrites it.

It looks like to you that it is working (since you are just cout'ing), but check the file, it will only have one entry in it - which is what the problem is.

So if you were to make that function:
bool WriteHighScoreToFile(SHigh_Score High_Score){	std::ofstream fout;	fout.open("highscores.dat",std::ios::binary | std::ios::app);	if (fout == NULL)		return 1;	fout.write((char*)(&High_Score), sizeof(SHigh_Score));	fout.close();	return 0;}

Instead, all of the high scores will be saved correctly. It will append all the entries as it is suppsed to. However, when you go to re-save all the scores again, you will just be appending, so you must delete the high score file beforehand.

To do that, you can make this function:
void ResetScoreBoard(){	for (int i=1; i<11; i++)	{		High_Scores[i-1].Rank = i;		High_Scores[i-1].Score = 0;		WriteHighScoreToFile(High_Scores[i-1]);	}}


Look like:
void ResetScoreBoard(){        // Reset the contents of the file        std::ofstream fout;        fout.open("highscores.dat",std::ios::binary);	fout.close(); 	for (int i=1; i<11; i++)	{		High_Scores[i-1].Rank = i;		High_Scores[i-1].Score = 0;		WriteHighScoreToFile(High_Scores[i-1]);	}}


So after you do all that it *should* work [wink]
Advertisement
changing your ResetScoreBoard function a little, it works fine

void ResetScoreBoard(){	std::ofstream fout;	fout.open("highscores.dat",std::ios::binary);	if (fout == NULL)		return;		for (int i=0; i<10; i++)	{		High_Scores.Rank = i + 1;		High_Scores.Score = 0;		fout.write((char*)(&High_Scores), sizeof(SHigh_Score));	}	fout.close();	}


Since you open the file in WriteHighScoreToFile() and then close it, it always writes to at the beginning, so you are only writing one entry in it. Instead keep the file open and do all your writing, then close it. Otherwise you have to scan to the spot in the file where you should be which is a hassle.
Aha! It works! Thank you, so much!

I guess I should have analized it more.

This topic is closed to new replies.

Advertisement