• Advertisement
Sign in to follow this  

File Read Errors

This topic is 1602 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement

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

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
Sign in to follow this  

  • Advertisement