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: /*
5: This uses the low level PetscBinaryWrite() and PetscBinaryRead() to access a binary file. It will not work in parallel!
7: We HIGHLY recommend using instead VecView() and VecLoad() to read and write Vectors in binary format (which also work in parallel). Then you can use
8: share/petsc/matlab/PetscBinaryRead() and share/petsc/matlab/PetscBinaryWrite() to read (or write) the vector into MATLAB.
10: Note this also works for matrices with MatView() and MatLoad().
11: */
12: #include <petscvec.h>
14: int main(int argc,char **args)
15: {
16: PetscMPIInt size;
17: int fd;
18: PetscInt i,m = 10,sz;
19: PetscScalar *avec,*array;
20: Vec vec;
21: PetscViewer view_out,view_in;
23: PetscInitialize(&argc,&args,(char*)0,help);
24: MPI_Comm_size(PETSC_COMM_WORLD,&size);
27: PetscOptionsGetInt(NULL,NULL,"-m",&m,NULL);
29: /* ---------------------------------------------------------------------- */
30: /* PART 1: Write some data to a file in binary format */
31: /* ---------------------------------------------------------------------- */
33: /* Allocate array and set values */
34: PetscMalloc1(m,&array);
35: for (i=0; i<m; i++) array[i] = i*10.0;
37: /* Open viewer for binary output */
38: PetscViewerBinaryOpen(PETSC_COMM_SELF,"input.dat",FILE_MODE_WRITE,&view_out);
39: PetscViewerBinaryGetDescriptor(view_out,&fd);
41: /* Write binary output */
42: PetscBinaryWrite(fd,&m,1,PETSC_INT);
43: PetscBinaryWrite(fd,array,m,PETSC_SCALAR);
45: /* Destroy the output viewer and work array */
46: PetscViewerDestroy(&view_out);
47: PetscFree(array);
49: /* ---------------------------------------------------------------------- */
50: /* PART 2: Read data from file and form a vector */
51: /* ---------------------------------------------------------------------- */
53: /* Open input binary viewer */
54: PetscViewerBinaryOpen(PETSC_COMM_SELF,"input.dat",FILE_MODE_READ,&view_in);
55: PetscViewerBinaryGetDescriptor(view_in,&fd);
57: /* Create vector and get pointer to data space */
58: VecCreate(PETSC_COMM_SELF,&vec);
59: VecSetSizes(vec,PETSC_DECIDE,m);
60: VecSetFromOptions(vec);
61: VecGetArray(vec,&avec);
63: /* Read data into vector */
64: PetscBinaryRead(fd,&sz,1,NULL,PETSC_INT);
67: PetscPrintf(PETSC_COMM_SELF,"reading data in binary from input.dat, sz =%" PetscInt_FMT " ...\n",sz);
68: PetscBinaryRead(fd,avec,sz,NULL,PETSC_SCALAR);
70: /* View vector */
71: VecRestoreArray(vec,&avec);
72: VecView(vec,PETSC_VIEWER_STDOUT_SELF);
74: /* Free data structures */
75: VecDestroy(&vec);
76: PetscViewerDestroy(&view_in);
77: PetscFinalize();
78: return 0;
79: }
81: /*TEST
83: test:
85: TEST*/