Actual source code: ex45.c

petsc-3.4.2 2013-07-02
  2: #include "petscconf.h"
  3: #include <stdio.h>
  4: #include <fcntl.h>
  5: #if defined(PETSC_HAVE_UNISTD_H)
  6: #include <unistd.h>
  7: #endif
  8: #include <stdlib.h>

 10: /*
 11:   Demonstrates dumping matrix/vector from heritage code for PETSc.
 12:    Note does not do bit swapping, so will not generate proper
 13: PETSc files on Paragon/Dec Alpha.
 14: */

 16: void Store2DArray(int,int,double*,const char*,int*);
 17: void Store1DArray(int,double*,const char*,int*);

 21: int main(int argc,char **args)
 22: {
 23:   double a[100],v[10];
 24:   int    i,j,fd = 0;

 26:   for (i=0; i<100; i++) {
 27:     a[i] = i + 1;
 28:   }
 29:   for (j=0; j<10; j++) {
 30:     v[j] = j;
 31:   }

 33:   Store2DArray(10,10,a,"array.dat",&fd);
 34:   Store1DArray(10,v,"array.dat",&fd);
 35:   return 0;
 36: }

 40: void Store2DArray(int m,int n,double *a,const char *filename,int *fdd)
 41: {
 42:   int    fd = *fdd;
 43:   int    i,j;
 44:   int    nz = -1,classid = 1211216;
 45:   double *vals;

 47:   if (!fd) {
 48:     fd = creat(filename,0666);
 49:     if (fd == -1) {
 50:       fprintf(stdout,"Unable to open binary file\n");
 51:       exit(0);
 52:     }
 53:     *fdd = fd;
 54:   }
 55:   write(fd,&classid,sizeof(int));
 56:   write(fd,&m,sizeof(int));
 57:   write(fd,&n,sizeof(int));
 58:   write(fd,&nz,sizeof(int));

 60:   /*
 61:      transpose the matrix, since it is stored by rows on the disk
 62:    */
 63:   vals = (double*) malloc(m*n*sizeof(double));
 64:   if (!vals) {
 65:     fprintf(stdout,"Out of memory ");
 66:     exit(0);
 67:   }
 68:   for (i=0; i<m; i++) {
 69:     for (j=0; j<n; j++) {
 70:       vals[i+m*j] = a[j+i*n];
 71:     }
 72:   }
 73:   write(fd,vals,m*n*sizeof(double));
 74:   free(vals);

 76: }

 80: void Store1DArray(int m,double *a,const char *filename,int *fdd)
 81: {
 82:   int fd      = *fdd;
 83:   int classid = 1211214;  /* classid for vectors */

 85:   if (fd == -1) {
 86:     fd = creat(filename,0666);
 87:     if (fd == -1) {
 88:       fprintf(stdout,"Unable to open binary file\n");
 89:       exit(0);
 90:     }
 91:     *fdd = fd;
 92:   }
 93:   write(fd,&classid,sizeof(int));
 94:   write(fd,&m,sizeof(int));
 95:   write(fd,a,m*sizeof(double));
 96: }