Actual source code: ex6.c

  2: static char help[] = "Writes an array to a file, then reads an array from a file, then forms a vector.\n\n";

 4:  #include petscvec.h

  8: int main(int argc,char **args)
  9: {
 11:   PetscMPIInt    size;
 12:   int            fd;
 13:   PetscInt       i,m = 10,sz;
 14:   PetscScalar    *avec,*array;
 15:   Vec            vec;
 16:   PetscViewer    view_out,view_in;

 18:   PetscInitialize(&argc,&args,(char *)0,help);
 19:   MPI_Comm_size(PETSC_COMM_WORLD,&size);
 20:   if (size != 1) SETERRQ(1,"This is a uniprocessor example only!");
 21: 
 22:   PetscOptionsGetInt(PETSC_NULL,"-m",&m,PETSC_NULL);

 24:   /* ---------------------------------------------------------------------- */
 25:   /*          PART 1: Write some data to a file in binary format            */
 26:   /* ---------------------------------------------------------------------- */

 28:   /* Allocate array and set values */
 29:   PetscMalloc(m*sizeof(PetscScalar),&array);
 30:   for (i=0; i<m; i++) {
 31:     array[i] = i*10.0;
 32:   }

 34:   /* Open viewer for binary output */
 35:   PetscViewerBinaryOpen(PETSC_COMM_SELF,"input.dat",FILE_MODE_WRITE,&view_out);
 36:   PetscViewerBinaryGetDescriptor(view_out,&fd);

 38:   /* Write binary output */
 39:   PetscBinaryWrite(fd,&m,1,PETSC_INT,PETSC_FALSE);
 40:   PetscBinaryWrite(fd,array,m,PETSC_SCALAR,PETSC_FALSE);

 42:   /* Destroy the output viewer and work array */
 43:   PetscViewerDestroy(view_out);
 44:   PetscFree(array);

 46:   /* ---------------------------------------------------------------------- */
 47:   /*          PART 2: Read data from file and form a vector                 */
 48:   /* ---------------------------------------------------------------------- */

 50:   /* Open input binary viewer */
 51:   PetscViewerBinaryOpen(PETSC_COMM_SELF,"input.dat",FILE_MODE_READ,&view_in);
 52:   PetscViewerBinaryGetDescriptor(view_in,&fd);

 54:   /* Create vector and get pointer to data space */
 55:   VecCreate(PETSC_COMM_SELF,&vec);
 56:   VecSetSizes(vec,PETSC_DECIDE,m);
 57:   VecSetFromOptions(vec);
 58:   VecGetArray(vec,&avec);

 60:   /* Read data into vector */
 61:   PetscBinaryRead(fd,&sz,1,PETSC_INT);
 62:   if (sz <=0) SETERRQ(1,"Error: Must have array length > 0");

 64:   PetscPrintf(PETSC_COMM_SELF,"reading data in binary from input.dat, sz =%D ...\n",sz);
 65:   PetscBinaryRead(fd,avec,sz,PETSC_SCALAR);

 67:   /* View vector */
 68:   VecRestoreArray(vec,&avec);
 69:   VecView(vec,PETSC_VIEWER_STDOUT_SELF);

 71:   /* Free data structures */
 72:   VecDestroy(vec);
 73:   PetscViewerDestroy(view_in);
 74:   PetscFinalize();
 75:   return 0;
 76: }