how can I save struct in file … C lang

前端 未结 6 850
悲&欢浪女
悲&欢浪女 2021-01-02 18:23

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   //         


        
6条回答
  •  感动是毒
    2021-01-02 18:58

    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;
    }
    

提交回复
热议问题