Actual source code: ex45.c

  1: /*$Id: ex45.c,v 1.11 2001/08/07 21:30:08 bsmith Exp $*/

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

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

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

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

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

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

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

 41:   if (!fd) {
 42:     fd = creat(filename,0666);
 43:     if (fd == -1) {
 44:       fprintf(stdout,"Unable to open binary filen");
 45:       exit(0);
 46:     }
 47:     *fdd = fd;
 48:   }
 49:   write(fd,&cookie,sizeof(int));
 50:   write(fd,&m,sizeof(int));
 51:   write(fd,&n,sizeof(int));
 52:   write(fd,&nz,sizeof(int));

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

 70: }

 72: void Store1DArray(int m,PetscReal *a,char *filename,int *fdd)
 73: {
 74:   int  fd = *fdd;
 75:   int  i,j,ierr;
 76:   int  cookie = 1211214; /* cookie for vectors */

 78:   if (fd == -1) {
 79:     fd = creat(filename,0666);
 80:     if (fd == -1) {
 81:       fprintf(stdout,"Unable to open binary filen");
 82:       exit(0);
 83:     }
 84:     *fdd = fd;
 85:   }
 86:   write(fd,&cookie,sizeof(int));
 87:   write(fd,&m,sizeof(int));
 88:   write(fd,a,m*sizeof(PetscReal));
 89: }