Hello, I am trying to serialize a simple C struct. I am dumping it to a file then try to read and restore it. However I got wrong data. Here is my idea:
Code:
#include <stdio.h>#include <stdlib.h>
#include <string.h>
struct a
{
int i;
char str[64];
struct
{
float x;
float y;
float z;
} vec3;
};
static struct a setA(int i, char* s, float f1, float f2, float f3)
{
struct a newa;
newa.i = i;
strcpy(newa.str, s);
newa.vec3.x = f1;
newa.vec3.y = f2;
newa.vec3.z = f3;
return newa;
}
static char* dumpA(struct a* pa)
{
union dmp {
struct a m_a;
char c[sizeof(struct a)];
} ;
union dmp d;
d.m_a.i = pa->i;
strcpy(d.m_a.str, pa->str);
d.m_a.vec3.x = pa->vec3.x;
d.m_a.vec3.y = pa->vec3.y;
d.m_a.vec3.z = pa->vec3.z;
int i =0;
static char dumped[sizeof(union dmp)];
FILE* fp = fopen("serialized", "wb");
if (!fp) {
return 0;
}
for(i=0; i < sizeof(d); i++) {
fprintf(fp, "%0x", d.c[i]);
dumped[i] = d.c[i];
}
fclose(fp);
return &dumped;
}
static void printA(struct a* pa)
{
printf("[%d][%s][%f;%f;%f]\n", pa->i, pa->str,
pa->vec3.x, pa->vec3.y, pa->vec3.z);
}
struct a* restoreA(char* fname)
{
return 0;
}
int main(int argc, char *argv[])
{
struct a newa = setA(1, "bla bla bla", 1.0, 2.0, 3.0);
printA(&newa);
char* odump = dumpA(&newa);
FILE *fp = fopen("serialized", "r");
char buff[256]={0};
while(fgets(buff, 256, fp)) {
}
union dm {
struct a ma;
char c[sizeof(struct a)];
};
union dm d;
memset(d.c, 0, sizeof(struct a));
strcpy(d.c, buff);
printf("[%d][%s][%f,%f,%f]\n", d.ma.i, d.ma.str,
d.ma.vec3.x, d.ma.vec3.y, d.ma.vec3.z);
fclose(fp);
return 0;
}
When I read it back it seems filled with data but the data is bad. In first time I don`t know if it is dumped correctly.