Go to the first, previous, next, last section, table of contents.


Use of the NetCDF Library

You can use the netCDF library without knowing about all of the netCDF interface. If you are creating a netCDF file, only a handful of routines are required to define the necessary dimensions, variables, and attributes, and to write the data to the netCDF file. (Even less are needed if you use the ncgen utility to create the file before running a program using netCDF library calls to write data.) Similarly, if you are writing software to access data stored in a particular netCDF object, only a small subset of the netCDF library is required to open the netCDF file and access the data. Authors of generic applications that access arbitrary netCDF files need to be familiar with more of the netCDF library.

In this chapter we provide templates of common sequences of netCDF subroutine calls needed for common uses. For clarity we present only the names of routines; omit declarations and error checking; indent statements that are typically invoked multiple times; and use ... to represent arbitrary sequences of other statements. Full argument lists for the procedures and subroutines are described in later chapters.

Creating a NetCDF File

The typical sequences of netCDF calls used to create a new netCDF file follows.

    nccreate      /* create netCDF file: enter define mode */
         ...
       ncdimdef   /* define dimension: from name and size */
         ...
       ncvardef   /* define variable: from name, type, dimensions */
         ...
       ncattput   /* put attribute: assign attribute values */
         ...
    ncendef       /* end definitions: leave define mode */
         ...
       ncvarput   /* put variable: provide values for variables */
         ...
    ncclose       /* close: save new netCDF file */

In FORTRAN, the corresponding sequence looks like this:

    NCCRE              ! create netCDF file: enter define mode
         ...
       NCDDEF          ! define dimensions: from name and size
         ...
       NCVDEF          ! define variables: from name, type, dimensions
         ...
       NCAPT or NCAPTC ! put attribute: assign attribute values
         ...
    NCENDF             ! end definitions: leave define mode
         ...
       NCVPT or NCVPTC ! put variable: provide values for variables
         ...
    NCCLOS             ! close: save new netCDF file

Only one call is needed to create a netCDF file, at which point you will be in the first of two netCDF modes. When accessing an open netCDF file, it is either in define mode or data mode. In define mode, you can create dimensions, variables, and new attributes, but you cannot read or write variable data. In data mode, you can access data and change existing attributes, but you are not permitted to create new dimensions, variables, or attributes.

One call to ncdimdef (or NCDDEF) is needed for each dimension created. Similarly, one call to ncvardef (or NCVDEF) is needed for each variable creation, and one call to ncattput (or NCAPT or NCAPTC) is needed for each attribute defined and assigned a value. To leave define mode and enter data mode, call ncendef (or NCENDF).

Once in data mode, you can add new data to variables, change old values, and change values of existing attributes (so long as the attribute changes do not require more storage space). The FORTRAN interface provides two subroutines for defining attributes and providing values for variables, depending on whether a numeric or character string value is used. Single values are written to a variable with ncvarput1 (or NCVPT1 or NCVP1C); while arbitrary arrays of data are written using ncvarput or ncvarputg (or NCVPT, NCVPTC, NCVPTG, or NCVPGC) instead. Multi-variable records of data may be written using multiple calls to ncvarput (or NCVPT) or with a single call to ncrecput.

Finally, you should explicitly close all netCDF files that have been opened for writing by calling ncclose (or NCCLOS). If a program terminates abnormally with netCDF files open for writing, you may lose one or more records of the most recently written record variable data as well as any attribute changes since the last call to ncsync (or NCSNC). It is possible to reduce the chance of losing data due to abnormal termination by explicitly calling ncsync (NCSNC) after every write to netCDF variables or change to attribute values. This can be expensive in computer resources, so such calls should ordinarily be omitted unless they are really needed.

Reading a NetCDF File with Known Names

Here we consider the case where you know the names of not only the netCDF files, but also the names of their dimensions, variables, and attributes. (Otherwise you would have to do "inquire" calls.) The order of typical C calls to read data from those variables in a netCDF file is:

    ncopen           /* open existing netCDF file */
         ...
       ncdimid       /* get dimension IDs */
         ...
       ncvarid       /* get variable IDs */
         ...
       ncattget      /* get attribute values */
         ...
       ncvarget      /* get values of variables */
         ...
    ncclose          /* close netCDF file */

In FORTRAN, the corresponding sequence looks like this:

    NCOPN               !  open existing netCDF file
         ...
       NCDID            !  get dimension IDs
         ...
       NCVID            !  get variable IDs
         ...
       NCAGT or NCAGTC  !  get attribute values
         ...
       NCVGT or NCVGTC  !  get values of variables
         ...
    NCCLOS              !  close netCDF file

First, a single call opens the netCDF file, given the file name, and returns a netCDF ID that is used to refer to the open netCDF file in all subsequent calls.

Next, a call to ncdimid (or NCDID) for each dimension of interest gets the dimension ID from the dimension name. Similarly, each required variable ID is determined from its name by a call to ncvarid (or NCVID). Once variable IDs are known, variable attribute values can be retrieved using the netCDF ID, the variable ID, and the desired attribute name as input to ncattget (or NCAGT or NCAGTC) for each desired attribute. Variable data values can be directly accessed from the netCDF file with ncvarget1 (or NCVGT1 or NCVG1C) for single values, ncvarget or ncvargetg (or NCVGT, NCVGTC, NCVGTG, or NCVGGC) for cross-sections of values, or ncrecget for records of values.

Finally, the netCDF file is closed with ncclose (or NCCLOS). There is no need to close a file open only for reading.

Reading a netCDF File with Unknown Names

Many programs (e.g. generic software) need to get It is possible to write programs (e.g. generic software) which do such things as processing every variable (except perhaps coordinate variables) in some way, without needing to know in advance the names of these variables. Even the names of dimensions and attributes may be unknown.

Names and other information may be obtained from netCDF files by calling inquire functions. These return information about a whole netCDF file, a dimension, a variable, or an attribute. The following template illustrates how they are used:

    ncopen           /* open existing netCDF file */
      ...
    ncinquire        /* find out what is in it */
         ...
       ncdiminq      /* get dimension names, sizes */
         ...
       ncvarinq      /* get variable names, types, shapes */
            ...
          ncattname  /* get attribute names */
            ...
          ncattinq   /* get attribute types and lengths */
            ...
          ncattget   /* get attribute values */
            ...
       ncvarget      /* get values of variables */
         ...
    ncclose          /* close netCDF file */

In FORTRAN, the corresponding sequence looks like this:

    NCOPN                 !  open existing netCDF file
      ...
    NCINQ                 !  find out what is in it
         ...
       NCDINQ             !  get dimension names, sizes
         ...
       NCVINQ             !  get variable names, types, shapes
            ...
          NCANAM          !  get attribute names
            ...
          NCAINQ          !  get attribute values
            ...
          NCAGT or NCAGTC !  get attribute values
            ...
       NCVGT or NCVGTC    !  get values of variables
         ...
    NCCLOS                !  close netCDF file

As in the previous example, a single call opens the existing netCDF file, returning a netCDF ID. This netCDF ID is given to the ncinquire (or NCINQ) routine, which returns the number of dimensions, the number of variables, the number of global attributes, and the ID of the unlimited dimension, if there is one.

Another inquire function, ncrecinq, provides a convenient way of obtaining information about record variables, although the information can also be obtained using the other inquire functions. The ncrecinq function returns the number of record variables, their variable IDs, and how much memory is needed for a data record.

All the inquire functions are quite inexpensive to use and require no I/O, since the information they provide is stored in memory. In the C interface, the inquire functions also support getting a subset of information, by providing null pointers instead of valid addresses, for undesired information.

Dimension IDs are assigned by using consecutive integers (beginning at 0 in C, 1 in FORTRAN). Also dimensions, once created, cannot be deleted. Therefore, knowing the number of dimension IDs in a netCDF file means knowing all the dimension IDs: they are the integers 0, 1, 2, ..., (or 1, 2, 3, ... in FORTRAN). For each dimension ID, a call to the inquire function ncdiminq (or NCDINQ) returns the dimension name and size.

Variable IDs are also assigned from consecutive integers 0, 1, 2, ..., (or 1, 2, 3, ... in FORTRAN). These can be used in ncvarinq (or NCVINQ) calls to find out the names, types, shapes, and the number of attributes assigned to each variable.

Once the number of attributes for a variable is known, successive calls to ncattname (or NCANAM) return the name for each attribute given the netCDF ID, variable ID, and attribute number. Armed with the attribute name, a call to ncattinq (or NCAINQ) returns its type and length. Given the type and length, you can allocate enough space to hold the attribute values. Then a call to ncattget (or NCAGT or NCAGTC) returns the attribute values.

Once the names, IDs, types, shapes, and lengths of all netCDF components are known, data values can be accessed by calling ncvarget1 (or NCVGT1 or NCVG1C) for single values, ncvarget or ncvargetg (or NCVGT, NCVGTC, NCVGTG, or NCVGGC) for aggregates of values using array access, or ncrecget for aggregates of values using record access.

Adding New Dimensions, Variables, Attributes

An existing netCDF file can be extensively altered. New dimensions, variables, and attributes can be added or existing ones renamed, and existing attributes can be deleted. Existing dimensions, variables, and attributes can be renamed. The following code template lists a typical sequence of calls to add new netCDF components to an existing file:

    ncopen           /* open existing netCDF file */
      ...
    ncredef          /* put it into define mode */
        ...
      ncdimdef       /* define additional dimensions (if any) */
        ...
      ncvardef       /* define additional variables (if any) */
        ...
      ncattput       /* define additional attributes (if any) */
        ...
    ncendef          /* check definitions, leave define mode */
        ...
      ncvarput       /* provide values for new variables */
        ...
    ncclose          /* close netCDF file */

In FORTRAN, the corresponding sequence looks like this:

    NCOPN             !  open existing netCDF file
      ...
    NCREDF            !  put it into define mode
        ...
      NCDDEF          !  define additional dimensions (if any)
        ...
      NCVDEF          !  define additional variables (if any)
        ...
      NCAPT or NCAPTC !  define additional attributes (if any)
        ...
    NCENDF            !  check definitions, leave define mode
        ...
      NCVPT or NCVPTC !  provide values for new variables
        ...
    NCCLOS            !  close netCDF file

A netCDF file is first opened by the ncopen (or NCOPN) call. This call puts you in data mode, which means existing data values can be accessed and changed, existing attributes can be changed (so long as they do not grow), but nothing can be added. To add new netCDF dimensions, variables, or attributes you must leave data mode and enter define mode, by calling ncredef (or NCREDF). In define mode, call ncdimdef (or NCDDEF) to define new dimensions, ncvardef (or NCVDEF) to define new variables, and ncattput (or NCAPT or NCAPTC) to assign new attributes to variables or enlarge old attributes.

You can leave define mode and reenter data mode, checking all the new definitions for consistency and committing the changes to disk, by calling ncendef (or NCENDF). If you do not wish to reenter data mode, just call ncclose (or NCCLOS), which will have the effect of first calling ncendef (or NCENDF).

Until the ncendef (or NCENDF) call, you may back out of all the redefinitions made in define mode and restore the previous state of the netCDF dataset by calling ncabort (or NCABOR). You may also use the ncabort call to restore the netCDF dataset to a consistent state if the call to ncendef (or NCENDF) fails. If you have called ncclose (or NCCLOS) from definition mode and the implied call to ncendef (or NCENDF) fails, ncabort (or NCABOR) will automatically be called to close the netCDF file and leave it in its previous consistent state (before you entered define mode).

Error Handling

The netCDF library provides the facilities needed to handle errors in a flexible way. However it is often unnecessary to specify anything about error handling, since by default all netCDF library routines just print an error message and exit when an error occurs. If this (admittedly drastic) error behavior is acceptable, you never need to check return values, since any condition that would result in an error will print an explanatory message and exit. For simplicity, the examples in this guide assume this default error-handling behavior, so there is no checking of return values.

In the C interface, errors may be handled more flexibly by setting the external integer ncopts, declared in the file `netcdf.h'. Two aspects of the error-handling behavior can be modified independently: the suppression of error messages, and the fatality of errors. The default behavior, that errors are both verbose and fatal, is specified by the assignment

ncopts = NC_VERBOSE | NC_FATAL;

where NC_VERBOSE and NC_FATAL are predefined constants from the include file `netcdf.h'.

If you want error messages but do not wish errors to be fatal, turn off the fatal error flag with:

ncopts = NC_VERBOSE;

If you want neither error messages nor fatal errors, turn off both flags with:

ncopts = 0;

In non-fatal mode you should check the return value after each call to a netCDF function. This value is 0 normally and -1 if an error occurs. Another externally-defined integer, ncerr, contains a netCDF-specific error code that is available after an error has occurred to determine the nature of the error. The names and descriptions of netCDF error codes are included in the file `netcdf.h'.

In the FORTRAN interface, the error options described above can be accessed by using the routines NCPOPT and NCGOPT. The default error- handling behavior is equivalent to the statement

      CALL NCPOPT(NCVERBOS+NCFATAL)

where the values of NCVERBOS and NCFATAL are predefined constants from the FORTRAN include file `netcdf.inc'. If you want error messages, but do not wish errors to be fatal, turn off the fatal error flag with:

      CALL NCPOPT(NCVERBOS)

If you want neither error messages nor fatal errors, turn off both flags with:

      CALL NCPOPT(0)

To get the current value of the error options, use:

      CALL NCGOPT(NCOPTS)

In either case, the integer return code (the last parameter in all of the FORTRAN subroutines and functions) contains the non-zero netCDF-specific error number that can be used to determine the nature of the error. Names and descriptions of netCDF error codes are included in the file `netcdf.inc'.

Occasionally, low-level write errors may occur in the XDR library layer below the netCDF library. For example, if a write operation causes you to exceed disk quotas or to attempt to write to a device that is no longer available, you may get an error message from one of the XDR functions rather than from the netCDF library.

Compiling and Linking with the NetCDF Library

Details of how to compile and link a program that uses the netCDF C or FORTRAN interfaces differ, depending on the operating system, the available compilers, and where the netCDF library and include files are installed. Nevertheless, we provide here examples of how to compile and link a program that uses the netCDF library on a Unix platform, so that you can adjust these examples to fit your installation.

C Interface

Every C file that references netCDF functions or constants must contain an appropriate #include statement before the first such reference:

#include <netcdf.h>

Unless the `netcdf.h' file is installed in a standard directory where the C compiler always looks, you must use the -I option when invoking the compiler, to specify a directory where `netcdf.h' is installed, for example:

cc -c -I/usr/local/netcdf/include myprogram.c

Alternatively, you could specify an absolute pathname in the #include statement, but then your program would not compile on another platform where netCDF is installed in a different location.

Unless the netCDF library is installed in a standard directory where the linker always looks, you must use the -L and -l options to link an object file that uses the netCDF library. For example:

cc -o myprogram myprogram.o -L/usr/local/netcdf/lib -lnetcdf

Alternatively, you could specify an absolute pathname for the library:

cc -o myprogram myprogram.o -l/usr/local/netcdf/lib/libnetcdf.a

On some systems, you must specify an additional library after the netCDF library where the system XDR libraries are found.

FORTRAN Interface

Every FORTRAN file that references netCDF functions or constants must contain an appropriate INCLUDE statement before the first such reference:

INCLUDE 'netcdf.inc'

Unless the `netcdf.inc' file is installed in a standard directory where the FORTRAN compiler always looks, you must use the -I option when invoking the compiler, to specify a directory where `netcdf.inc' is installed, for example:

f77 -c -I/usr/local/netcdf/include myprogram.f

Alternatively, you could specify an absolute pathname in the INCLUDE statement, but then your program would not compile on another platform where netCDF is installed in a different location.

Unless the netCDF library is installed in a standard directory where the linker always looks, you must use the -L and -l options to link an object file that uses the netCDF library. For example:

f77 -o myprogram myprogram.o -L/usr/local/netcdf/lib -lnetcdf

Alternatively, you could specify an absolute pathname for the library:

f77 -o myprogram myprogram.o -l/usr/local/netcdf/lib/libnetcdf.a

On some systems, you must specify an additional library after the netCDF library where the system XDR libraries are found.


Go to the first, previous, next, last section, table of contents.