Actual source code: ex6.c

  1: /*$Id: ex6.c,v 1.33 2001/08/07 03:02:34 balay Exp $*/

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

 5:  #include petscvec.h

  7: int main(int argc,char **args)
  8: {
  9:   int         i,ierr,m = 10,fd,size,sz;
 10:   PetscScalar *avec,*array;
 11:   Vec         vec;
 12:   PetscViewer view_out,view_in;

 14:   PetscInitialize(&argc,&args,(char *)0,help);
 15:   MPI_Comm_size(PETSC_COMM_WORLD,&sz);
 16:   if (sz != 1) SETERRQ(1,"This is a uniprocessor example only!");
 17: 
 18:   PetscOptionsGetInt(PETSC_NULL,"-m",&m,PETSC_NULL);

 20:   /* ---------------------------------------------------------------------- */
 21:   /*          PART 1: Write some data to a file in binary format            */
 22:   /* ---------------------------------------------------------------------- */

 24:   /* Allocate array and set values */
 25:   PetscMalloc(m*sizeof(PetscScalar),&array);
 26:   for (i=0; i<m; i++) {
 27:     array[i] = i*10.0;
 28:   }

 30:   /* Open viewer for binary output */
 31:   PetscViewerBinaryOpen(PETSC_COMM_SELF,"input.dat",PETSC_BINARY_CREATE,&view_out);
 32:   PetscViewerBinaryGetDescriptor(view_out,&fd);

 34:   /* Write binary output */
 35:   PetscBinaryWrite(fd,&m,1,PETSC_INT,0);
 36:   PetscBinaryWrite(fd,array,m,PETSC_SCALAR,0);

 38:   /* Destroy the output viewer and work array */
 39:   PetscViewerDestroy(view_out);
 40:   PetscFree(array);

 42:   /* ---------------------------------------------------------------------- */
 43:   /*          PART 2: Read data from file and form a vector                 */
 44:   /* ---------------------------------------------------------------------- */

 46:   /* Open input binary viewer */
 47:   PetscViewerBinaryOpen(PETSC_COMM_SELF,"input.dat",PETSC_BINARY_RDONLY,&view_in);
 48:   PetscViewerBinaryGetDescriptor(view_in,&fd);

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

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

 60:   PetscPrintf(PETSC_COMM_SELF,"reading data in binary from input.dat, size =%d ...n",size);
 61:   PetscBinaryRead(fd,avec,size,PETSC_SCALAR);

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

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