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: #undef __FUNCT__
  9: int main(int argc,char **args)
 10: {
 11:   int         i,ierr,m = 10,fd,size,sz;
 12:   PetscScalar *avec,*array;
 13:   Vec         vec;
 14:   PetscViewer view_out,view_in;

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

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

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

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

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

 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",PETSC_BINARY_RDONLY,&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,&size,1,PETSC_INT);
 60:   if (size <=0) SETERRQ(1,"Error: Must have array length > 0");

 62:   PetscPrintf(PETSC_COMM_SELF,"reading data in binary from input.dat, size =%d ...n",size);
 63:   PetscBinaryRead(fd,avec,size,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: }