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;
24: PetscInitialize(&argc, &args, (char *)0, help);
25: MPI_Comm_size(PETSC_COMM_WORLD, &size);
28: PetscOptionsGetInt(NULL, NULL, "-m", &m, NULL);
30: /* ---------------------------------------------------------------------- */
31: /* PART 1: Write some data to a file in binary format */
32: /* ---------------------------------------------------------------------- */
34: /* Allocate array and set values */
35: PetscMalloc1(m, &array);
36: for (i = 0; i < m; i++) array[i] = i * 10.0;
38: /* Open viewer for binary output */
39: PetscViewerBinaryOpen(PETSC_COMM_SELF, "input.dat", FILE_MODE_WRITE, &view_out);
40: PetscViewerBinaryGetDescriptor(view_out, &fd);
42: /* Write binary output */
43: PetscBinaryWrite(fd, &m, 1, PETSC_INT);
44: PetscBinaryWrite(fd, array, m, PETSC_SCALAR);
46: /* Destroy the output viewer and work array */
47: PetscViewerDestroy(&view_out);
48: PetscFree(array);
50: /* ---------------------------------------------------------------------- */
51: /* PART 2: Read data from file and form a vector */
52: /* ---------------------------------------------------------------------- */
54: /* Open input binary viewer */
55: PetscViewerBinaryOpen(PETSC_COMM_SELF, "input.dat", FILE_MODE_READ, &view_in);
56: PetscViewerBinaryGetDescriptor(view_in, &fd);
58: /* Create vector and get pointer to data space */
59: VecCreate(PETSC_COMM_SELF, &vec);
60: VecSetSizes(vec, PETSC_DECIDE, m);
61: VecSetFromOptions(vec);
62: VecGetArray(vec, &avec);
64: /* Read data into vector */
65: PetscBinaryRead(fd, &sz, 1, NULL, PETSC_INT);
68: PetscPrintf(PETSC_COMM_SELF, "reading data in binary from input.dat, sz =%" PetscInt_FMT " ...\n", sz);
69: PetscBinaryRead(fd, avec, sz, NULL, PETSC_SCALAR);
71: /* View vector */
72: VecRestoreArray(vec, &avec);
73: VecView(vec, PETSC_VIEWER_STDOUT_SELF);
75: /* Free data structures */
76: VecDestroy(&vec);
77: PetscViewerDestroy(&view_in);
78: PetscFinalize();
79: return 0;
80: }
82: /*TEST
84: test:
86: TEST*/