next up previous contents
Next: The MINC format Up: An Introduction to NetCDF Previous: The NetCDF file   Contents

Programming with NetCDF

Programming with NetCDF can be quite simple. The file listed above was produced by the following program:

#include <netcdf.h>

#define THE_NAME "My favorite tiny image"
static double vals[][4]={
   1.0, 2.0, 3.0, 4.0,
   5.0, 6.0, 7.0, 8.0,
static int ysize=sizeof(vals)/sizeof(vals[0]);
static int xsize=sizeof(vals[0])/sizeof(vals[0][0]);

static double xcoord[]={100.,200.,300.,400.};

   int cdf, img, xvar;
   int dim[MAX_VAR_DIMS];
   long count[MAX_VAR_DIMS], start[MAX_VAR_DIMS];

   /* Create the file */

   /* Define the dimensions */
   dim[0]=ncdimdef(cdf, "ycoord", ysize);
   dim[1]=ncdimdef(cdf, "xcoord", xsize);

   /* Define the variables */
   img=ncvardef(cdf, "image", NC_DOUBLE, 2, dim);
   xvar=ncvardef(cdf,"xcoord", NC_DOUBLE, 1, &dim[1]);

   /* Add an attribute */
   ncattput(cdf, img, "long_name", NC_CHAR, strlen(THE_NAME)+1, THE_NAME);

   /* End definition mode */

   /* Write the variable values */
   count[0]=ysize; count[1]=xsize;
   ncvarput(cdf, img, start, count, vals);
   ncvarput(cdf, xvar, &start[1], &count[1], xcoord);

The first executable line of the program creates a new NetCDF file. An open file is either in ``define'' mode or in ``data'' mode. In define mode, dimensions, variables and attributes can be defined, but data cannot be written to or read from variables. In data mode, variable values can be written or read, but no changes to dimensions or variables can be made and attributes can only be written if they exist already and will not get larger with the write. Newly created files are automatically in define mode.

The lines following the call to nccreate define the dimensions and variables in the file. Notice that the NetCDF file, dimensions and variables are all identified by an integer returned when they are created. These id's are subsequently used to refer to each object. The attribute ``long_name'' for the image variable is identified only by its name.

Once everything is defined, ncendef puts the file into data mode and values are written. The values to write are defined by a vector of starting indices and a vector of the number of values to write in each dimension. This defines a multi-dimensional rectangle within the variable called a hyperslab. In the C interface, the first element of the vector refers to the slowest varying index of the variable, so in this example, the array vals has the xcoord varying fastest. In the FORTRAN interface, the convention has the first subscript varying fastest. These conventions follow the language conventions for multi-dimensional arrays.

next up previous contents
Next: The MINC format Up: An Introduction to NetCDF Previous: The NetCDF file   Contents
Robert VINCENT 2004-05-28