Next: , Previous: Reading Unknown, Up: Use of the NetCDF Library


1.4 Writing Data in an Existing NetCDF Dataset

With write access to an existing netCDF dataset, you can overwrite data values in existing variables or append more data to record variables along the unlimited (record) dimension. To append more data to non-record variables requires changing the shape of such variables, which means creating a new netCDF dataset, defining new variables with the desired shape, and copying data. The netCDF data model was not designed to make such "schema changes" efficient or easy, so it is best to specify the shapes of variables correctly when you create a netCDF dataset, and to anticipate which variables will later grow by using the unlimited dimension in their definition.

The following code template lists a typical sequence of calls to overwrite some existing values and add some new records to record variables in an existing netCDF dataset with known variable names:

          NF90_OPEN             ! open existing netCDF dataset
            ...
            NF90_INQ_VARID      ! get variable IDs
            ...
            NF90_PUT_VAR        ! provide new values for variables, if any
            ...
            NF90_PUT_ATT        ! provide new values for attributes, if any
              ...
          NF90_CLOSE            ! close netCDF dataset

A netCDF dataset is first opened by the NF90_OPEN call. This call puts the open dataset in data mode, which means existing data values can be accessed and changed, existing attributes can be changed, but no new dimensions, variables, or attributes can be added.

Next, calls to NF90_INQ_VARID get the variable ID from the name, for each variable you want to write. Then each call to NF90_PUT_VAR writes data into a specified variable, either a single value at a time, or a whole set of values at a time, depending on which variant of the interface is used. The calls used to overwrite values of non-record variables are the same as are used to overwrite values of record variables or append new data to record variables. The difference is that, with record variables, the record dimension is extended by writing values that don't yet exist in the dataset. This extends all record variables at once, writing "fill values" for record variables for which the data has not yet been written (but see Fill Values to specify different behavior).

Calls to NF90_PUT_ATT may be used to change the values of existing attributes, although data that changes after a file is created is typically stored in variables rather than attributes.

Finally, you should explicitly close any netCDF datasets into which data has been written by calling NF90_CLOSE before program termination. Otherwise, modifications to the dataset may be lost.