Actual source code: ex45.c
1: /*$Id: ex45.c,v 1.11 2001/08/07 21:30:08 bsmith Exp $*/
3: #include <stdio.h>
4: #include <fcntl.h>
5: #include <unistd.h>
6: #include <stdlib.h>
8: /*
9: Demonstrates dumping matrix/vector from heritage code for PETSc.
10: Note does not do bit swapping, so will not generate proper
11: PETSc files on Paragon/Dec Alpha.
12: */
14: EXTERN void Store2DArray(int,int,PetscReal*,char*,int *);
15: EXTERN void Store1DArray(int,PetscReal*,char*,int *);
19: int main(int argc,char **args)
20: {
21: PetscReal a[100],v[10];
22: int i,j,fd = 0;
24: for (i=0; i<100; i++) {
25: a[i] = i + 1;
26: }
27: for (j=0; j<10; j++) {
28: v[j] = j;
29: }
31: Store2DArray(10,10,a,"array.dat",&fd);
32: Store1DArray(10,v,"array.dat",&fd);
33: return 0;
34: }
38: void Store2DArray(int m,int n,PetscReal *a,char *filename,int *fdd)
39: {
40: int fd = *fdd;
41: int i,j;
42: int nz = -1,cookie = 1211216,ierr;
43: PetscReal *vals;
45: if (!fd) {
46: fd = creat(filename,0666);
47: if (fd == -1) {
48: fprintf(stdout,"Unable to open binary file\n");
49: exit(0);
50: }
51: *fdd = fd;
52: }
53: write(fd,&cookie,sizeof(int));
54: write(fd,&m,sizeof(int));
55: write(fd,&n,sizeof(int));
56: write(fd,&nz,sizeof(int));
58: /*
59: transpose the matrix, since it is stored by rows on the disk
60: */
61: PetscMalloc(m*n*sizeof(PetscReal), &vals);
62: if (!vals) {
63: fprintf(stdout,"Out of memory ");
64: exit(0);
65: }
66: for (i=0; i<m; i++) {
67: for (j=0; j<n; j++) {
68: vals[i+m*j] = a[j+i*n];
69: }
70: }
71: write(fd,vals,m*n*sizeof(PetscReal));
72: PetscFree(vals);
74: }
78: void Store1DArray(int m,PetscReal *a,char *filename,int *fdd)
79: {
80: int fd = *fdd;
81: int i,j,ierr;
82: int cookie = 1211214; /* cookie for vectors */
84: if (fd == -1) {
85: fd = creat(filename,0666);
86: if (fd == -1) {
87: fprintf(stdout,"Unable to open binary file\n");
88: exit(0);
89: }
90: *fdd = fd;
91: }
92: write(fd,&cookie,sizeof(int));
93: write(fd,&m,sizeof(int));
94: write(fd,a,m*sizeof(PetscReal));
95: }