Date: 2013-07-02T14:40:18+00:00

Actual source code: ex6.c
petsc-3.4.2 2013-07-02

      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(PETSC_COMM_SELF,1,"This is a uniprocessor example only!");

     22:   PetscOptionsGetInt(NULL,"-m",&m,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++) array[i] = i*10.0;

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

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

     40:   /* Destroy the output viewer and work array */
     41:   PetscViewerDestroy(&view_out);
     42:   PetscFree(array);

     44:   /* ---------------------------------------------------------------------- */
     45:   /*          PART 2: Read data from file and form a vector                 */
     46:   /* ---------------------------------------------------------------------- */

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

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

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

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

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

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