Previous: The Simple XY Write Example in C Next: Creating a NetCDF Dataset Table of contents Frames 2010 Unidata NetCDF Workshop > Introduction to the NetCDF APIs and Example Programs

9.19 The Simple XY Example in C++
C++ code that writes the simple_xy.nc example dataset.

 

#include <iostream>
#include <netcdfcpp.h>

using namespace std;

static const int NX = 6;
static const int NY = 12;
static const int NC_ERR = 2;

int 
main(void)
{
   int dataOut[NX][NY];
   for(int i = 0; i < NX; i++) 
      for(int j = 0; j < NY; j++)
	 dataOut[i][j] = i * NY + j;

   NcFile dataFile("simple_xy.nc", NcFile::Replace);

   // You should always check whether a netCDF file creation or open
   // constructor succeeded.
   if (!dataFile.is_valid())
   {
      cout << "Couldn't open file!\n";
      return NC_ERR;
   }
  
   // For other method calls, the default behavior of the C++ API is
   // to exit with a message if there is an error.  If that behavior
   // is OK, there is no need to check return values in simple cases
   // like the following.

   // When we create netCDF dimensions, we get back a pointer to an
   // NcDim for each one.
   NcDim* xDim = dataFile.add_dim("x", NX);
   NcDim* yDim = dataFile.add_dim("y", NY);
  
   NcVar *data = dataFile.add_var("data", ncInt, xDim, yDim);
   data->put(&dataOut[0][0], NX, NY);

   // The file will be automatically closed when the NcFile object goes
   // out of scope.
   return 0;
}

 


Previous: The Simple XY Write Example in C Next: Creating a NetCDF Dataset Table of contents Frames 2010 Unidata NetCDF Workshop > Introduction to the NetCDF APIs and Example Programs