2007 Unidata NetCDF Workshop for Developers and Data Providers > NetCDF Example Programs
6.8 The Simple XY Example in C++
The C++ code which writes the simple_xy.nc example dataset.
#include
#include
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 close when the NcFile object goes
// out of scope.
return 0;
}
2007 Unidata NetCDF Workshop for Developers and Data Providers > NetCDF Example Programs