save a struct

hi all ,
can i save a structure in c in a file? how ?

help me , thx. :slight_smile:

Yeah, you can.

Say you have a struct variable named s. You could simply write/read from ((void*)&s) to (((void*)&s) + sizeof s) using whatever I/O functions. But there are 2 problems with that.

1) Some compilers will produce code that use "sparse" structs. structs with holes in them, that is. This is to make the code faster. Memory accesses that is aligned at some power of 2 multiple is usually faster, for example. If the compiler or compiler settings were to change, the sparseness may change too and old data files would become incompatible.

2) This method will create data files that are architecture-dependent. Fundamental C types, like pointers, ints, floats, etc, won't read/write the same on different architecture. So the data files will not be portable.

So it would be better to encode your data in a standard way. There are a few ways to do that:

1) Just read/write your stuff using ASCII printable chars. You could use scanf(3)/printf(3) for that.

2) Check xdr(3) (eXternal Data Representation); that's what is used for rpc(3) (Remote Procedure Call). It can encode/decode your stuff automatically.

3) Use some library that uses XML format. That's the current hype.

By save, do you mean write the data in it to a file?
Try something like this:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
    struct {
        char a[20];
        int b;
     } mystruct;
    FILE *out;
    char *somestring="A test value";
    memset(mystruct.a,0x0,sizeof(mystruct.a));
    strcpy(mystruct.a,somestring);
    mystruct.b = 8;
    out=fopen("myfile","wb");
    if(out==NULL)
    {
        perror("");
        exit(EXIT_FAILURE);
    }
    fwrite(&mystruct,sizeof(mystruct),1,out);
    if(fclose(out)!=0)
    {
       perror("");
       exit(EXIT_FAILURE);
    }

    return 0;
}

To see what is in the file try

od myfile