Actual source code: ex6.c
1: /*$Id: ex6.c,v 1.31 2001/04/10 19:35:06 bsmith 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: Scalar *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(Scalar),&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,PETSC_DECIDE,m,&vec);
52: VecSetFromOptions(vec);
53: VecGetArray(vec,&avec);
55: /* Read data into vector */
56: PetscBinaryRead(fd,&size,1,PETSC_INT);
57: if (size <=0) SETERRQ(1,"Error: Must have array length > 0");
59: PetscPrintf(PETSC_COMM_SELF,"reading data in binary from input.dat, size =%d ...n",size);
60: PetscBinaryRead(fd,avec,size,PETSC_SCALAR);
62: /* View vector */
63: VecRestoreArray(vec,&avec);
64: VecView(vec,PETSC_VIEWER_STDOUT_SELF);
66: /* Free data structures */
67: VecDestroy(vec);
68: PetscViewerDestroy(view_in);
69: PetscFinalize();
70: return 0;
71: }