I already gave you some code, but OK, it was incomplete. Let's try a plain, not object oriented, C-Like approach:
#include
enum SerialType
{
eTYPE_UNRECOGNIZED,
eTYPE_A,
eTYPE_B,
eTYPE_C,
eTYPES
};
struct A
{
int id;
int data;
};
struct B
{
int id;
float data;
};
struct C
{
int id;
double data;
int data2;
};
size_t getSize(SerialType st)
{
switch( st)
{
case eTYPE_A:
return sizeof(A);
case eTYPE_B:
return sizeof(B);
case eTYPE_C:
return sizeof(C);
default:
return 0;
}
}
bool store( SerialType st, void * pData, FILE * fp)
{
int type = st;
size_t size = getSize(st);
if (!fp || !pData || !size) return false;
fwrite(&type, sizeof(type), 1, fp);
fwrite(pData, size,1,fp);
return true;
}
SerialType readType( FILE * fp)
{
SerialType type;
if (!fp ) return eTYPE_UNRECOGNIZED;
if ( fread(&type, sizeof(type), 1, fp) == 0 ) return eTYPE_UNRECOGNIZED;
return type;
}
bool readData( SerialType st, void * pData, FILE * fp)
{
size_t size = getSize(st);
if ( !fp || !pData || !size ) return false;
fread(pData, size, 1, fp);
return true;
}
void main()
{
SerialType type;
A a[2];
B b;
C c1,c2;
A * pa=NULL;
B * pb=NULL;
C * pc=NULL;
// define some variables
a[0].data = 5;
a[0].id = 12;
a[1].data = 6;
a[1].id = 13;
b.data=25.75f;
b.id=100;
c1.data = 27;
c1.data2=35;
c1.id = 7;
c2.data=1000.372;
c2.data2=1000;
c2.id=1;
FILE * fp = fopen("data.raw", "wb");
// store some of the defined variables
store(eTYPE_C, &c2, fp);
store(eTYPE_A, &a[1], fp);
store(eTYPE_B, &b, fp);
store(eTYPE_A, &a[0], fp);
fclose(fp);
// read the variables from the storage, printing their values.
fp = fopen("data.raw", "rb");
while ((type=readType(fp)) != eTYPE_UNRECOGNIZED)
{
switch (type)
{
case eTYPE_A:
pa = new A();
readData(type, pa, fp);
printf("type A, id=%d, data=%d.\n", pa->id, pa->data);
delete pa;
break;
case eTYPE_B:
pb = new B();
readData(type, pb, fp);
printf("type B, id=%d, data=%g.\n", pb->id, pb->data);
delete pb;
break;
case eTYPE_C:
pc = new C();
readData(type, pc, fp);
printf("type C, id=%d, data=%g, data2=%d.\n", pc->id, pc->data, pc->data2);
delete pb;
break;
}
}
fclose(fp);
}
<