nezvers

serialize in C - save/load array binary

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