Skip to content

PnetCDF example programs in C

Wei-keng Liao edited this page Feb 10, 2023 · 2 revisions

C programming flow for creating a new file

Create a new file, named "testfile.nc".
  MPI_Comm comm = MPI_COMM_OWRLD;
  char *filename = "testfile.nc";
  MPI_Info info = MPI_INFO_NULL;
  int cmode, ncid;
  cmod = NC_CLOBBER | NC_64BIT_DATA;
  ncmpi_create(comm, filename, cmode, info, &ncid);
Define two dimensions, namely "lat" and "lon".
  MPI_Offset latitude  = 100;
  MPI_Offset logtitude = 100;
  int dimid[2];
  ncmpi_def_dim(ncid, "lat", latitude,  &dimid[0]);
  ncmpi_def_dim(ncid, "lon", logtitude, &dimid[1]);
Define a 2D variable of size 100x100.
  int varid;
  ncmpi_def_var(ncid, "topo", NC_FLOAT, 2, dimid, &varid);
Add two attributes to the variable "topo".
  char *attr = "grid cell topography";
  ncmpi_put_att_text(ncid, varid, "long_name", strlen(attr), attr);
  attr = "m"; /* unit in meters */
  ncmpi_put_att_text(ncid, varid, "units", strlen(attr), attr);
Exit define mode and enter data mode.
  ncmpi_enddef(ncid);
Write a subarray of size 10x20 to variable "topo".
  int rank;
  float buf[10][20];
  MPI_Offset start[2], count[2];
  MPI_Comm_rank(comm, &rank);
  start[0] = 0;
  start[1] = 5 * rank;
  count[0] = 10;
  count[1] = 20;
  ncmpi_put_vara_float_all(ncid, varid, start, count, &buf[0][0]);
Close the file.
  ncmpi_close(ncid);
Clone this wiki locally