C Code to write VTK Structured Grid

This simple C code is used to write out a 2-D array (A) of size N to an ASCII file. The legacy VTK data file format is used. The data is written out as structured grid (which is also known as a curvilinear grid).

 1.void Write_VTK_Structured_Grid(float *x, float *y, float *A, int ni, int nj, const char *filename)
 2.{
 3.   FILE *out;
 4.   out = fopen(filename,"w");
 5.   fprintf(out,"# vtk DataFile Version 3.0\n");
 6.   fprintf(out,"Insert Any Information Here.\n");
 7.   fprintf(out,"ASCII\n");
 8.   fprintf(out,"DATASET STRUCTURED_GRID\n");
 9.   fprintf(out,"DIMENSIONS %d %d %d\n",ni,nj,1);
10.    fprintf(out,"POINTS %d float\n",ni*nj);
11.    for(i=0;i<ni;i++) {
12.     for(j=0;j<nj;j++) {
13.      index = j*ni + i;
14.      fprintf(out,"%f %f %f\n",x[index],y[index],0.0);
15.     }
16.    }
17.    fprintf(out,"POINT_DATA %d\n",ni*nj);
18.    fprintf(out,"SCALARS scalar_name float 1\n");
19.    fprintf(out,"LOOKUP_TABLE default\n");
20.    for(i=0; i<ni*nj; i++) {
21.      fprintf(out,"%f\n",A[i]);
22.    }
23.    fclose(out);
24. }

Back to Types of Grids