Why is there a NULL at end of my binary file?

Started by
5 comments, last by Zahlman 17 years, 5 months ago
All the times before I explicitly stated in by binary files how many items should be found in that file. I decided this time to loop until eof is reached. The problem is there is an extra NULL character at the end of the file, so the loop goes back and tries to load the first value - leaving the rest blank. I don't know where this extra NULL character is coming from. Here is the code I am using:
int Scoreboard::load(const char *filename)
{
	Score score;
	ifstream file;
			
	file.open(filename, ios::in | ios::binary);
	if (file.is_open())
	{
		score_list.clear();

		while (!file.eof())
		{
			getline(file, score.name, '\0');
			file.read((char*) &score.score, sizeof(unsigned int));

			score_list.push_back(score);
		}

		file.close();

		return true;
	}

	return false;
}


int Scoreboard::save(const char *filename)
{
	ofstream file;

	file.open(filename, ios::out | ios::binary);
	if (file.is_open())
	{
		vector<Score>::iterator i;

		for (i=score_list.begin(); i!=score_list.end(); i++)
		{
			file << i->name << '\0';
			file.write((char*) &i->score, sizeof(unsigned int));
		}

		file.close();

		return true;
	}

	return false;
}
Advertisement
Oops. Maybe there isn't an extra NULL at the end. I looked at the resulting file in a Hex editor again, and I guess I miscounted the number of bytes that was used in the last unsigned int. Still, though, why does it try loading one more entry than there really is?
Maybe eof() doesn't return true until you've tried to read past the end?

Also, a couple of notes:
Assuming Score::score is an unsigned int, you can use
sizeof(score.score)
instead of
sizeof(unsigned int)

That makes it robust to you changing the type of the score member.

I've read that ++i may be more efficient than i++ for iterators (it may depend on if your compiler optimizes the i++, knowing that no one uses the old value).
Why is there a NULL in the getline?
Phil_t, that's what I was thinking. The eof function might not return true until after reading past the end.

Anonymous Poster, I just wanted to use null terminated strings instead of new-line terminated string -- for no real reason.
While exploring the possibilities of why eof wasn't working as expected I found this article:
http://www.daniweb.com/techtalkforums/post155265-18.html
0)
1)
2)

This topic is closed to new replies.

Advertisement