NetCDF: Difference between revisions

Jump to navigation Jump to search
2,367 bytes added ,  6 years ago
Line 69: Line 69:


=== Example ===
=== Example ===
{{
<syntaxhighlight lang="cpp" line highlight="1,2,7">
File |name=ex_netcdf4.c |language=c |contents=
/**
}}
Write the simple_xy file, with some of the features of netCDF-4.
This is a very simple example which is based on the simple_xy example,
but whch uses netCDF-4 features, such as compression.
This program writes a 2D netCDF variable (called "data") and fills it
with sample data.  It has two dimensions, "x" and "y".
Full documentation for netCDF can be found at:
http://www.unidata.ucar.edu/netcdf/docs
*/
#include <stdlib.h>
#include <stdio.h>
#include <netcdf.h>
/* Name of the file which will be created */
#define FILE_NAME "simple_xy_nc4.nc"
/* We write 2D data on a 60 x 120 grid */
#define NDIMS 2
#define NX 60
#define NY 120
/* Define how to handle errors */
#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];
  size_t chunks[NDIMS];
  int shuffle, deflate, deflate_level;
  int data_out[NX][NY];
  int x, y, retval;
  /* Set the data layout */
  shuffle = NC_SHUFFLE;
  deflate = 1;
  deflate_level = 1;
  /* Create some nonsense data for testing purposes */
  for (x = 0; x < NX; x++)
      for (y = 0; y < NY; y++)
        data_out[x][y] = x * NY + y;
  /* Create the file. The NC_NETCDF4 parameter indicates that the file type is NetCDF-4/HDF5 */
  if ((retval = nc_create(FILE_NAME, NC_NETCDF4, &ncid)))
      ERR(retval);
  /* Define the dimensions */
  if ((retval = nc_def_dim(ncid, "x", NX, &x_dimid)))
      ERR(retval);
  if ((retval = nc_def_dim(ncid, "y", NY, &y_dimid)))
      ERR(retval);
  /* Create the variables */
  dimids[0] = x_dimid;
  dimids[1] = y_dimid;
  chunks[0] = NX/4;
  chunks[1] = NY/4;
  /* Define the variables */
  if ((retval = nc_def_var(ncid, "data", NC_INT, NDIMS,
                            dimids, &varid)))
      ERR(retval);
  if ((retval = nc_def_var_chunking(ncid, varid, 0, &chunks[0])))
      ERR(retval);
  if ((retval = nc_def_var_deflate(ncid, varid, shuffle, deflate,
                                    deflate_level)))
      ERR(retval);
  /* Write the data to the file */
  if ((retval = nc_put_var_int(ncid, varid, &data_out[0][0])))
      ERR(retval);
  /* Close the file */
  if ((retval = nc_close(ncid)))
      ERR(retval);
  printf("*** SUCCESS in writing the file simple_xy_nc4.nc!\n");
  return 0;
}
</syntaxhighlight>
Bureaucrats, cc_docs_admin, cc_staff
337

edits

Navigation menu