Sign in to follow this  
Waffler

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

Recommended Posts

Waffler    127
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;
}

Share this post


Link to post
Share on other sites
Waffler    127
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?

Share this post


Link to post
Share on other sites
phil_t    8084
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).

Share this post


Link to post
Share on other sites
Waffler    127
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this