Actual source code: ex45.c

petsc-3.8.4 2018-03-24
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 PETSc files on some systems.
 16: */

 18: void Store2DArray(int,int,double*,const char*,int*);
 19: 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: }

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

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

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

 74: }

 76: void Store1DArray(int m,double *a,const char *filename,int *fdd)
 77: {
 78:   int     fd = *fdd;
 79:   int     classid = 1211214;  /* classid for vectors */

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