Mega Code Archive

 
Categories / C / Code Snippets
 

Save array in memory into file

#include <stdio.h> #include <stdlib.h> int main(void) { int j; double *p; FILE *filep; /* get memory */ p = malloc(10 * sizeof(double)); if(!p) { printf("Allocation Error"); exit(1); } /* generate 10 random numbers */ for(j = 0; j < 10; j++) p[j] = (double) rand(); if((filep = fopen("myfile.txt", "wb")) == NULL) { printf("Cannot open file.\n"); exit(1); } /* write the entire array in one step */ if( fwrite(p, 10*sizeof(double), 1, filep) != 1) { printf("Write Error.\n"); exit(1); } fclose(filep); free(p); /* free memory */ /* get memory again */ p = malloc(10 * sizeof(double)); if(!p) { printf("Allocation Error"); exit(1); } if((filep = fopen("myfile.txt", "rb"))==NULL) { printf("Cannot open file.\n"); exit(1); } /* read the entire array in one step */ if(fread(p, 10 * sizeof( double ), 1, filep) != 1) { printf( " Read Error.\n " ); exit( 1 ); } fclose( filep ); /* display the array */ for(j = 0; j < 10; j++) printf("%f ", p[ j ]); free(p); return 0; }