Sign in to follow this  
Six222

File Read Errors

Recommended Posts

I'm having some problems with reading a binary file, I keep getting an unhandled exception in XUtility.h. It reads the first sections of the file fine, but when it goes out of scope it crashes?

 

Here's my code:

void ViewEnts() {
	system("CLS");
	cout << "Entity List" << endl;
	
	ifstream file("entities.entl", ios::in | ios::binary);
	if(file.is_open()) {
		EntityHeader head;
		file.read((char*)&head, sizeof(EntityHeader));
		
		for(int x = 0; x != head.num; x++) {
			EntityStructure ent;
			file.read((char*)&ent, sizeof(EntityStructure));

			cout << "Entity " << x << ") " << ent.className << endl;
			cout << "Renderable: " << ent.isRenderable << endl;
			cout << "Script Location: " << ent.scriptLocation << endl;
			system("PAUSE");
			
		} //CRASHES HERE 
	} else {
		cout << "FATAL ERROR OCCURED: COULD NOT OPEN FILE" << endl;
		system("PAUSE");
	}

	file.close();
	system("PAUSE");
}

Also if I make "EntityStructure ent;" a global variable it will read the whole file fine until I exit the program which it then will crash?

Edited by Six222

Share this post


Link to post
Share on other sites

The headers look like:

struct EntityHeader {
	int num;
};

struct EntityStructure{
	std::string className;
	std::string scriptLocation;
	bool isRenderable;
};

But I think I've worked it out.. I changed from using strings to char's and now it seems to work fine.

Share this post


Link to post
Share on other sites

But I think I've worked it out.. I changed from using strings to char's and now it seems to work fine.

 

Thats because std::string is far away from being POD, so I highly doubt that it can, in any form be serialized directly in a binary way. The problem here is that both className and scriptLocation are being read in from invalid data, e.g. pointer to memory locations that don't exist any more from the point where they were saved, and so when the loop goes out of scope, the temporary variable is destroyed, and the std::string destructor is trying to clean up the mess that was just constructed, which it can't. Thus the exception, and thus why it works until the progams exit if you make ent a global variable.

Edited by Juliean

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