Previous: Some Common Errors to Avoid Next: Write The Simple XY Example in F90 Table of contents Frames 2012 Unidata NetCDF Workshop > Using netCDF in programs

11.5 The Simple XY Write Example in C
A C example program that writes the simple_xy.nc example dataset.

 

#include <stdlib.h>
#include <stdio.h>
#include <netcdf.h>

#define FILE_NAME "simple_xy.nc"
#define NDIMS 2
#define NX 6
#define NY 12
#define ERRCODE 2
#define ERR(e) {printf("Error: %s\n", nc_strerror(e)); exit(ERRCODE);}

int
main()
{
   int ncid, x_dimid, y_dimid, varid;
   int dimids[NDIMS];
   int data_out[NX][NY];
   int x, y, retval;

   for (x = 0; x < NX; x++)
      for (y = 0; y < NY; y++)
	 data_out[x][y] = x * NY + y;

   if ((retval = nc_create(FILE_NAME, NC_CLOBBER, &ncid)))
      ERR(retval);

   if ((retval = nc_def_dim(ncid, "x", NX, &x_dimid)))
      ERR(retval);
   if ((retval = nc_def_dim(ncid, "y", NY, &y_dimid)))
      ERR(retval);

   dimids[0] = x_dimid;
   dimids[1] = y_dimid;
   if ((retval = nc_def_var(ncid, "data", NC_INT, NDIMS, 
			    dimids, &varid)))
      ERR(retval);

   if ((retval = nc_enddef(ncid)))
      ERR(retval);

   if ((retval = nc_put_var_int(ncid, varid, &data_out[0][0])))
      ERR(retval);

   if ((retval = nc_close(ncid)))
      ERR(retval);

   return 0;
}

 


Previous: Some Common Errors to Avoid Next: Write The Simple XY Example in F90 Table of contents Frames 2012 Unidata NetCDF Workshop > Using netCDF in programs