File Read Errors

Started by
2 comments, last by Juliean 10 years, 7 months ago

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?

Advertisement

What does EntityHeader look like? If it's not POD then just reading bits from the stream may be corrupting its state.

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.


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.

This topic is closed to new replies.

Advertisement