it is not necessary to specify both a beginning and an end, only length. the next beginning can be inferred from the previous end.
Code:
class Hello
{
public:
Hello() :
str(0)
{
}
Hello(char *_str,float _x):
str(_str),
x(_x)
{
}
~Hello()
{
if(str)
{
delete str;
}
}
char *str;
float x;
};
int serializeHello(Hello& h,const char *filePath)
{
char*index=h.str;
while(*index)
{
index++;
}
unsigned int strLen = (unsigned int)index-(unsigned int)h.str;
std::ofstream out(filePath,std::ios_base::out|std::ios_base::binary);
if(!out.is_open())
{
return -1;
}
out.write((char*)&strLen,sizeof(unsigned int));
if(strLen++)
{
out.write(h.str,strLen);
}
out.write((char*)&h.x,sizeof(float));
return out.tellp();
}
Hello deserializeHello(const char *filePath)
{
std::ifstream in(filePath,std::ios_base::in|std::ios_base::binary);
unsigned int i;
in.read((char*)&i,sizeof(unsigned int));
char* str=0;
if(i++)
{
str = new char[i];
in.read(str,i);
}
float x;
in.read((char*)&x,sizeof(float));
return Hello(str,x);
}
int _tmain(int argc, _TCHAR* argv[])
{
char *asdf = "asdf";
char*str = new char[5];
memcpy(str,asdf,5);
Hello h(str,1.234);
if(serializeHello(h,"hello")>0)
{
Hello h2 = deserializeHello("hello");
}
system("pause");
return 0;
}