How can I save a struct with pointers(what is pointed to aswell) to a file - C -
iam trying create program can save information pointed in file. i'am able load , use later.
here struct 2 structs:
typedef struct{ char name[11]; char efternamn[11]; }person; typedef struct{ int numbofpersons; person * personlist; }persongod; persongod controller; int choice; { printf("(1) initialize x amount of persons\n" "(3) save\n" "(5) load controller\n"); scanf("%d", &choice); switch (choice) { case 1 : initializepersons(&controller); break; case 3 : savepersonstofile(&controller); break; case 5 : loadcontroller(&controller); break; } } while(flag);
here functions load,save, initialize:
void initializepersons(persongod* controller) { int amount, i; printf("how many persons created"); fscanf(stdin, "%d", &amount); controller->personlist = (person*)calloc(amount, sizeof(person)); for(i=0; < amount; i++) { printf("name: "); fscanf(stdin, "%s", controller->personlist[i].name); printf("lastname: "); fscanf(stdin, "%s", controller->personlist[i].efternamn); //eftername=lastname } controller->numbofpersons = amount; // update how many persons current have } void savepersonstofile(persongod* controller) { file* fileptr; if((fileptr = fopen("c:\\users\\x\\desktop\\openstruct\\persons", "r+b"))== null) { fprintf(stderr, "error opening file: %s\n", strerror( errno )); exit(0); } if(fwrite(controller, sizeof(persongod), 1, fileptr)<1) fprintf(stderr, "%s\n", strerror( errno )); fclose(fileptr); } void loadcontroller(persongod* controller) { file* fileptr; if((fileptr = fopen("c:\\users\\x\\desktop\\openstruct\\persons", "r+b"))== null) { fprintf(stderr, "error opening file: %s\n", strerror( errno )); exit(0); } if(fread(controller, sizeof(persongod), 1, fileptr)<1){ fprintf(stderr, "%s\n", strerror( errno )); } fclose(fileptr); }
what happen when save->closeprogram->open->load numofpersons correct , personlist point not allocated memory anymore , crash.
having hard time googling how accomplish this.
how save&restore pointed data
you never want write raw pointer data files since if re-run program later (or on machine, use compiler etc.), there no guarantee objects have same addresses.
so, need write fields separately, since fwrite has no idea of type of data want write. indicated first parameter of fwrite type const void*
.
an example (minus error handling):
fwrite(&controller->numberofpersons, sizeof(controller->numberofpersons), 1, fileptr); fwrite(controller->personlist, sizeof(*controller->personlist), controller->numberofpersons, fileptr);
for reading file use same logic:
fread(&controller->numberofpersons, sizeof(controller->numberofpersons), 1, fileptr); controller->personlist = calloc(controller->numberofpersons, sizeof(*controller->personlist); fread(controller->personlist, sizeof(*controller->personlist), controller->numberofpersons, fileptr);
this solution have problems endianness, it's not portable, story.
Comments
Post a Comment