Actual source code: ex45.c

  2: #include <stdio.h>
  3: #include <fcntl.h>
  4: #include <unistd.h>
  5: #include <stdlib.h>

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

 13: EXTERN void Store2DArray(int,int,PetscReal*,char*,int *);
 14: EXTERN void Store1DArray(int,PetscReal*,char*,int *);

 18: int main(int argc,char **args)
 19: {
 20:   PetscReal a[100],v[10];
 21:   int       i,j,fd = 0;

 23:   for (i=0; i<100; i++) {
 24:     a[i] = i + 1;
 25:   }
 26:   for (j=0; j<10; j++) {
 27:     v[j] = j;
 28:   }

 30:   Store2DArray(10,10,a,"array.dat",&fd);
 31:   Store1DArray(10,v,"array.dat",&fd);
 32:   return 0;
 33: }

 37: void Store2DArray(int m,int n,PetscReal *a,char *filename,int *fdd)
 38: {
 39:   int        fd = *fdd;
 40:   int        i,j;
 41:   int        nz = -1,cookie = 1211216,ierr;
 42:   PetscReal *vals;

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

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

 73: }

 77: void Store1DArray(int m,PetscReal *a,char *filename,int *fdd)
 78: {
 79:   int  fd = *fdd;
 80:   int  i,j,ierr;
 81:   int  cookie = 1211214; /* cookie for vectors */

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