First there's nothing "crazy" about that output. Don't expect any "magic" happening, writing a struct to a file just does write exactly how the struct is stored in RAM, byte by byte.
Second, that's almost never what you want, because the layout in memory for a struct
will differ from machine to machine, sometimes even from compiler to compiler. For writing structs to a file and reading them back reliably, you have to do some sort of (de-)serialization using only textual representations of all individual fields.
Very basic example of (de-)serializing a struct
:
This example is really minimal and stores a struct
in a file line-by-line, assuming the struct and all pointer fields are allocated dynamically. I didn't test this code, it might have a bug, just to show a simple idea.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct data
{
int id;
char *name;
char *value;
} data;
static char *copyInput(char *buf)
{
char *copy;
size_t endpos = strlen(buf) - 1;
while (buf[endpos] == '\r' || buf[endpos] == '\n')
{
buf[endpos] = 0;
--endpos;
}
copy = malloc(strlen(buf) + 1);
strcpy(copy, buf);
return copy;
}
data *data_deserialize(FILE *fp)
{
char buf[256];
data *d = calloc(1, sizeof(*d));
if (!d) return 0;
if (!fgets(buf, 256, fp)) goto err;
d->id = atoi(buf);
if (!fgets(buf, 256, fp)) goto err;
d->name = copyInput(buf);
if (!fgets(buf, 256, fp)) goto err;
d->value = copyInput(buf);
return d;
err:
free(d->name);
free(d->value);
free(d);
return 0;
}
int data_serialize(FILE *fp, const data *d)
{
int rc;
rc = fprintf(fp, "%d\n", d->id);
if (rc < 0) return rc;
rc = fprintf(fp, "%s\n", d->name);
if (rc < 0) return rc;
rc = fprintf(fp, "%s\n", d->value);
return rc;
}