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 //
I realize this is an old post, but it comes up when people search for this information, so I'll give my own solution.
This is basically what I have used in one of my games. I actually have some extra library specific code in my own function for dialogs, but this is essentially it. I write data individually. I don't think I have a struct for this data, but there is no difference, just write your individual struct members separately. As mentioned, it's better this way.
// returns 1 if successful, 0 if not
int savemap(const char *map_name)
{
FILE *file = NULL;
// open the file in write binary mode
file = fopen(map_name, "wb");
// always check return values to see if it was opened okay
if(file == NULL) {
fprintf(stderr, "Error opening file for writing.\n");
return 0;
}
// write file ID, version and pills
fwrite(MAP_ID, sizeof(char), strlen(MAP_ID)+1, file);
fwrite(&MAP_VER, sizeof(unsigned char), 1, file);
fwrite(&pills, sizeof(unsigned short), 1, file);
// write the map data (unsigned int map[315])
fwrite(&map, sizeof(unsigned int), 315, file);
// never forget to close the file
fclose(file);
return 1;
}