Save file as binary data

Hello,

I have an Obj object and I've written the following functions to save the data of the object in binary form

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
void Obj::saveDataBinary(std::string filename){
	std::ofstream outFile(filename, std::ios_base::binary);
	outFile.write(mName.c_str(), sizeof(char)*256);
	outFile.write((char*)&mHitPoints, sizeof(int));
	outFile.write((char*)&mMagicPoints, sizeof(int));
	outFile.write((char*)&mArmor, sizeof(int));
	outFile.close();

}

void Obj::loadDataBinary(std::string filename){
	char* cName = new char[256];
	std::ifstream inFile(filename, std::ios_base::binary);
	inFile.read(cName, sizeof(char)*256);
	inFile.read((char*)&mHitPoints, sizeof(int));
	inFile.read((char*)&mMagicPoints, sizeof(int));
	inFile.read((char*)&mArmor, sizeof(int));
	inFile.close();
	for(int i = 0; i < mName.length(); i++){
		if(cName[i] == '\0'){
			for(int j = i; j < mName.length(); j++){
				mName[j] = '\0';
			}
			break;
		}
		mName[i] = cName[i];
	}
	//mName[mName.length()] = '\0';
}


This piece of code works correctly but I do not like the implementation. As can be seen, I try to save a string in binary format and that isn't a problem. The problem is when I try to load the data back into that string.
Two problems:
1. It doesn't let me read the binary data directly into the string. i.e. it doesn't accept,
inFile.read((char*)mName, sizeof(char)*256);
I guess this may be due to the size issue which brings me to the next problem
2. I do not know the size of that prior string that I saved. I used the null character at the end of the string to determine this. But then I have to make sure mName is of a large enough size.

One work around I can think of is to have this objects name limited to 25 or so characters and so I always know the size of the string.

Any suggestions as to how I should deal with saving strings in binary format??? Or whether strings are the way to go about saving object names?

Thanks

K

EDIT: I'm thinking if I save an int of the name size prior to the name then I can know the size of the string I need.
Last edited on
Topic archived. No new replies allowed.