Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Github: https://github.com/nezvers
- Youtube: https://www.youtube.com/channel/UCb4-Y0E6mmwjtawcitIAzKQ
- Twitter: https://twitter.com/NeZversStudio
- */
- #include <stdio.h>
- #include <stdlib.h>
- void write_text(){
- FILE *fp;
- char str[] = "This is serialization first test \nI wonder how it looks like.";
- fp = fopen( "file.txt" , "w" );
- fwrite(str , 1 , sizeof(str) , fp );
- fclose(fp);
- }
- void load_text(){
- FILE *fp;
- int c;
- fp = fopen("file.txt","r");
- while(1) {
- c = fgetc(fp);
- if( feof(fp) ) {
- break ;
- }
- printf("%c", c);
- }
- fclose(fp);
- }
- typedef struct{
- int dataSize;
- int *data;
- }myData;
- void Serialize(){
- int nums[] = {0,1,2,3,4,5,6,7,8,9}; //Array to save
- myData toSave = {0}; //init struct
- toSave.dataSize = sizeof(nums)/sizeof(int); //mark count of entries
- toSave.data = nums; //assign array to save
- FILE* fp = fopen("myData.sav","wb"); //prepare file to write binary
- fwrite(&toSave.dataSize, sizeof(toSave.dataSize), 1, fp); //write entries count
- fwrite(toSave.data, sizeof(int)*toSave.dataSize, 1, fp); //write the data
- fclose(fp); //close the file
- }
- void DeSerialize(){
- myData toLoad = {0}; //init struct
- FILE* fp = fopen("myData.sav","rb"); //prepare file to read binary
- fread(&toLoad.dataSize, sizeof(int), 1, fp); //read(point to variable, size, how many entries, point to file)
- toLoad.data = (int*)calloc(toLoad.dataSize, sizeof(int)); //allocate memory for incoming data
- 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)
- fclose(fp); //close file
- for(int i = 0; i < toLoad.dataSize; i++){
- printf("%i", i);
- }
- free(fp); //free allocated memory
- }
- int main () {
- Serialize();
- DeSerialize();
- printf("\nDone\n");
- return(0);
- }
Add Comment
Please, Sign In to add comment