Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I save struct in file .... C lang

Tags:

c

file

pointers

I'd like to save a struct in a file. I'd like to realize a function which makes this work. I tried this code but it didn't work.

struct utilisateur   // enregestrement pour sauvegarder les details de l utilisateur
{
 char nom[20];
 char prenom[20];
 int place;
 char depart[20];
 char arrive[20];
 char sexe;
 int nwagon;
};

struct utilisateur utilis;
struct utilisateur *Table[48];

void crea_fich(struct utilisateur *Tutilis)
// creation un fichier, vous introduiez le nom, et le sotcker par enreg
{
    FILE *f;
    if (f!==0)
    {
         printf("error in the name of file \n");
         exit(1);
    }
    if (f=fopen(futilis,"w")==Null){
         fprint("We can't creat file \n");
         exit(1);
    }
    else{
        f=fopen("futilis.dat","wb");
        fwrite(Tutilis ,sizeof(utilisateur),1,f);
    }
}
like image 220
TZttt Avatar asked Jul 29 '09 23:07

TZttt


1 Answers

No. You need to write out your data members individually, one at a time. You should not just blindly copy the memory representation of your struct into the file output buffer (which it is clear you are trying to do). Writing files that way will cause the files to non-portable (they won't be readable except on the platform that they were written), because of the endian-ness and the platform-specific padding of the struct elements.

like image 120
Michael Aaron Safyan Avatar answered Nov 15 '22 08:11

Michael Aaron Safyan