
#include <stdio.h>
#include <stdlib.h>

int main () {
  FILE * fp;
  long int file_size;
  size_t result;
  double * buffer;
							// open file
  if ((fp = fopen("binary_x","rb"))==NULL) {
        printf("Cannot open file.\n");
        exit(1);
  }

  // obtain file size:
  fseek ( fp , 0 , SEEK_END );
  file_size = ftell ( fp );
  rewind ( fp );

  printf("%ld bytes in file\n",file_size );
  printf("%ld sizeof double\n", sizeof(double));
  
  /* allocate memory to contain the whole file:*/
  if (( buffer =(double *) malloc( file_size)) == NULL) {
	printf("Cannot open file.\n");
        exit(1);
  }

  /* copy the file into the buffer: */
  buffer =(double *)malloc(file_size);
  if ((result=fread(buffer,sizeof(double),file_size/sizeof(double),fp)) != (file_size/sizeof(double)) ) {
  printf("Read Error fread crash.\n");
        exit(1);
  }
  fclose ( fp );
  printf("%ld doubles read\n",(long)result);
  
  /* the whole file is now loaded in the memory buffer. */
  /* debug
  printf("\n");
  for ( int i = 0 ; i < result ; i++ ){
  	if (((i % 4) ==0 ) && (i!=0)) printf("\n");
  	printf("%lf ", buffer[i]);
	}
  printf("\n");
  */
  // terminate
  
  //free ( buffer ); 

  if ((fp = fopen("test_dump_x","w"))==NULL) {
        printf("Cannot open file.\n");
        exit(1);
  }
  for (int i = 0 ; i <result ; i++ ){
      if (((i % 4)==0) && (i!=0)) fprintf(fp,"\n");  				// write to file
      fprintf (fp ,"%lf " ,buffer[i]);
  }
  //fclose (fp);
  return 0;
}


