Actual source code: ex45.c

petsc-3.6.1 2015-08-06
Report Typos and Errors
  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: #if defined(PETSC_HAVE_IO_H)
  9: #include <io.h>
 10: #endif
 11: #include <stdlib.h>

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

 19: void Store2DArray(int,int,double*,const char*,int*);
 20: void Store1DArray(int,double*,const char*,int*);

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

 29:   for (i=0; i<100; i++) {
 30:     a[i] = i + 1;
 31:   }
 32:   for (j=0; j<10; j++) {
 33:     v[j] = j;
 34:   }

 36:   Store2DArray(10,10,a,"array.dat",&fd);
 37:   Store1DArray(10,v,"array.dat",&fd);
 38:   return 0;
 39: }

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

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

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

 79: }

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

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