nezvers

serialize in C - save/load array binary

Oct 28th, 2020
1,047
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. void write_text(){
  5.     FILE *fp;
  6.     char str[] = "This is serialization first test \nI wonder how it looks like.";
  7.  
  8.     fp = fopen( "file.txt" , "w" );
  9.     fwrite(str , 1 , sizeof(str) , fp );
  10.  
  11.     fclose(fp);
  12. }
  13.  
  14. void load_text(){
  15.     FILE *fp;
  16.     int c;
  17.  
  18.     fp = fopen("file.txt","r");
  19.     while(1) {
  20.         c = fgetc(fp);
  21.         if( feof(fp) ) {
  22.          break ;
  23.         }
  24.         printf("%c", c);
  25.     }
  26.     fclose(fp);
  27. }
  28.  
  29. typedef struct{
  30.     int dataSize;
  31.     int *data;
  32. }myData;
  33.  
  34. void Serialize(){
  35.     int nums[] = {0,1,2,3,4,5,6,7,8,9};                         //Array to save
  36.    
  37.     myData toSave = {0};                                        //init struct
  38.     toSave.dataSize = sizeof(nums)/sizeof(int);                 //mark count of entries
  39.     toSave.data = nums;                                         //assign array to save        
  40.    
  41.     FILE* fp = fopen("myData.sav","wb");                        //prepare file to write binary
  42.     fwrite(&toSave.dataSize, sizeof(toSave.dataSize), 1, fp);   //write entries count
  43.     fwrite(toSave.data, sizeof(int)*toSave.dataSize, 1, fp);    //write the data
  44.     fclose(fp);                                                 //close the file
  45. }
  46.  
  47. void DeSerialize(){
  48.     myData toLoad = {0};                                        //init struct
  49.    
  50.     FILE* fp = fopen("myData.sav","rb");                        //prepare file to read binary
  51.     fread(&toLoad.dataSize, sizeof(int), 1, fp);                //read(point to variable, size, how many entries, point to file)
  52.     toLoad.data = (int*)calloc(toLoad.dataSize, sizeof(int));   //allocate memory for incoming data
  53.     fread(toLoad.data, sizeof(int) * toLoad.dataSize, toLoad.dataSize, fp); //read data (point to data pointer, size of entries * count, how many entries, point to file)
  54.     fclose(fp);                                                 //close file
  55.    
  56.     for(int i = 0; i < toLoad.dataSize; i++){
  57.         printf("%i", i);
  58.     }
  59.     free(fp);                                                   //free allocated memory
  60. }
  61.  
  62. int main () {
  63.     Serialize();
  64.     DeSerialize();
  65.     printf("\nDone\n");
  66.     return(0);
  67. }
RAW Paste Data