[Next] [Previous] [Top] [Contents] [Index] [netCDF Home Page][Unidata Home Page]

NetCDF User's Guide for C

5 Datasets


This chapter presents the interfaces of the netCDF functions that deal with a netCDF dataset or the whole netCDF library.

A netCDF dataset that has not yet been opened can only be referred to by its dataset name. Once a netCDF dataset is opened, it is referred to by a netCDF ID, which is a small nonnegative integer returned when you create or open the dataset. A netCDF ID is much like a file descriptor in C or a logical unit number in FORTRAN. In any single program, the netCDF IDs of distinct open netCDF datasets are distinct. A single netCDF dataset may be opened multiple times and will then have multiple distinct netCDF IDs; however at most one of the open instances of a single netCDF dataset should permit writing. When an open netCDF dataset is closed, the ID is no longer associated with a netCDF dataset.

Functions that deal with the netCDF library include:

The operations supported on a netCDF dataset as a single object are:

After a summary of conventions used in describing the netCDF interfaces, the rest of this chapter presents a detailed description of the interfaces for these operations.

5.1 NetCDF Library Interface Descriptions


Each interface description for a particular netCDF function in this and later chapters contains:

The examples follow a simple convention for error handling, always checking the error status returned from each netCDF function call and calling a handle_error function in case an error was detected. For an example of such a function, see Section 5.2 "Get error message corresponding to error status: nc_strerror," page 30.

5.2 Get error message corresponding to error status: nc_strerror


The function nc_strerror returns a static reference to an error message string corresponding to an integer netCDF error status or to a system error number, presumably returned by a previous call to some other netCDF function. The list of netCDF error status codes is available in the appropriate include file for each language binding.

Usage

const char * nc_strerror(int ncerr);
ncerrAn error status that might have been returned from a previous call to some netCDF function.
Errors

If you provide an invalid integer error status that does not correspond to any netCDF error message or or to any system error message (as understood by the system strerror function), nc_strerror returns a string indicating that there is no such error status.

Example

Here is an example of a simple error handling function that uses nc_strerror to print the error message corresponding to the netCDF error status returned from any netCDF function call and then exit:

#include <netcdf.h>
   ... 
void handle_error(int status) {
if (status != NC_NOERR) {
   fprintf(stderr, "%s\n", nc_strerror(status));
   exit(-1);
   }
}

5.3 Get netCDF library version: nc_inq_libvers


The function nc_inq_libvers returns a string identifying the version of the netCDF library, and when it was built.

Usage

const char * nc_inq_libvers(void);
Errors

This function takes no arguments, and thus no errors are possible in its invocation.

Example

Here is an example using nc_inq_libvers to print the version of the netCDF library with which the program is linked:

#include <netcdf.h>
   ... 
   printf("%s\n", nc_inq_libvers());

5.4 Create a NetCDF dataset: nc_create


This function creates a new netCDF dataset, returning a netCDF ID that can subsequently be used to refer to the netCDF dataset in other netCDF function calls. The new netCDF dataset opened for write access and placed in define mode, ready for you to add dimensions, variables, and attributes.

A creation mode flag specifies whether to overwrite any existing dataset with the same name and whether access to the dataset is shared.

Usage

int nc_create (const char* path, int cmode, int *ncidp);
pathThe file name of the new netCDF dataset.
cmodeThe creation mode. A zero value (or NC_CLOBBER) specifies the default behavior: overwrite any existing dataset with the same file name and buffer and cache accesses for efficiency.

Otherwise, the creation mode is NC_NOCLOBBER, NC_SHARE, or NC_NOCLOBBER|NC_SHARE. Setting the NC_NOCLOBBER flag means you do not want to clobber (overwrite) an existing dataset; an error (NC_EEXIST) is returned if the specified dataset already exists. The NC_SHARE flag is appropriate when one process may be writing the dataset and one or more other processes reading the dataset concurrently; it means that dataset accesses are not buffered and caching is limited. Since the buffering scheme is optimised for sequential access, programs that do not access data sequentially may see some performance improvement by setting the NC_SHARE flag.

ncidpPointer to location where returned netCDF ID is to be stored.
Errors

nc_create returns the value NC_NOERR if no errors occurred. Possible causes of errors include:

Example

In this example we create a netCDF dataset named foo.nc; we want the dataset to be created in the current directory only if a dataset with that name does not already exist:

#include <netcdf.h>
   ... 
int status;
int ncid;
   ... 
status = nc_create("foo.nc", NC_NOCLOBBER, &ncid);
if (status != NC_NOERR) handle_error(status);

5.5 Open a NetCDF Dataset for Access: nc_open


The function nc_open opens an existing netCDF dataset for access.

Usage

int nc_open (const char *path, int omode, int *ncidp);
pathFile name for netCDF dataset to be opened.
omodeA zero value (or NC_NOWRITE) specifies the default behavior: open the dataset with read-only access, buffering and caching accesses for efficiency

Otherwise, the creation mode is NC_WRITE, NC_SHARE, or NC_WRITE|NC_SHARE. Setting the NC_WRITE flag opens the dataset with read-write access. ("Writing" means any kind of change to the dataset, including appending or changing data, adding or renaming dimensions, variables, and attributes, or deleting attributes.) The NC_SHARE flag is appropriate when one process may be writing the dataset and one or more other processes reading the dataset concurrently; it means that dataset accesses are not buffered and caching is limited. Since the buffering scheme is optimised for sequential access, programs that do not access data sequentially may see some performance improvement by setting the NC_SHARE flag.

ncidpPointer to location where returned netCDF ID is to be stored.
Errors

nc_open returns the value NC_NOERR if no errors occurred. Otherwise, the returned status indicates an error. Possible causes of errors include:

Example

Here is an example using nc_open to open an existing netCDF dataset named foo.nc for read-only, non-shared access:

#include <netcdf.h>
   ... 
int status;
int ncid;
   ... 
status = nc_open("foo.nc", 0, &ncid);
if (status != NC_NOERR) hendle_error(status);

5.6 Put Open NetCDF Dataset into Define Mode: nc_redef


The function nc_redef puts an open netCDF dataset into define mode, so dimensions, variables, and attributes can be added or renamed and attributes can be deleted.

Usage

int nc_redef(int ncid);
ncidnetCDF ID, from a previous call to nc_open or nc_create.
Errors

nc_redef returns the value NC_NOERR if no errors occurred. Otherwise, the returned status indicates an error. Possible causes of errors include:

Example

Here is an example using nc_redef to open an existing netCDF dataset named foo.nc and put it into define mode:

#include <netcdf.h>
   ... 
int status;
int ncid;
   ... 
status = nc_open("foo.nc", NC_WRITE, &ncid);  /* open dataset */
if (status != NC_NOERR) handle_error(status);
   ... 
status = nc_redef(ncid);                      /* put in define mode */
if (status != NC_NOERR) handle_error(status);

5.7 Leave Define Mode: nc_enddef


The function nc_enddef takes an open netCDF dataset out of define mode. The changes made to the netCDF dataset while it was in define mode are checked and committed to disk if no problems occurred. Non-record variables may be initialized to a "fill value" as well (see Section 5.12 "Set Fill Mode for Writes: nc_set_fill," page 39). The netCDF dataset is then placed in data mode, so variable data can be read or written.

This call may involve copying data under some circumstances. See Chapter 9 "NetCDF File Structure and Performance," page 95, for a more extensive discussion.

Usage

int nc_enddef(int ncid);
ncidNetCDF ID, from a previous call to nc_open or nc_create.
Errors

nc_enddef returns the value NC_NOERR if no errors occurred. Otherwise, the returned status indicates an error. Possible causes of errors include:

Example

Here is an example using nc_enddef to finish the definitions of a new netCDF dataset named foo.nc and put it into data mode:

#include <netcdf.h>
   ... 
int status;
int ncid;
   ... 
status = nc_create("foo.nc", NC_NOCLOBBER, &ncid);
if (status != NC_NOERR) handle_error(status);

   ...       /* create dimensions, variables, attributes */

status = nc_enddef(ncid);  /*leave define mode*/
if (status != NC_NOERR) handle_error(status);

5.8 Close an Open NetCDF Dataset: nc_close


The function nc_close closes an open netCDF dataset. If the dataset is in define mode, nc_enddef will be called before closing. (In this case, if nc_enddef returns an error, nc_abort will automatically be called to restore the dataset to the consistent state before define mode was last entered.) After an open netCDF dataset is closed, its netCDF ID may be reassigned to the next netCDF dataset that is opened or created.

Usage

int nc_close(int ncid);
ncidNetCDF ID, from a previous call to nc_open or nc_create.
Errors

nc_close returns the value NC_NOERR if no errors occurred. Otherwise, the returned status indicates an error. Possible causes of errors include:

Example

Here is an example using nc_close to finish the definitions of a new netCDF dataset named foo.nc and release its netCDF ID:

#include <netcdf.h>
   ... 
int status;
int ncid;
   ... 
status = nc_create("foo.nc", NC_NOCLOBBER, &ncid);
if (status != NC_NOERR) handle_error(status);

   ...       /* create dimensions, variables, attributes */

status = nc_close(ncid);       /* close netCDF dataset */
if (status != NC_NOERR) handle_error(status);

5.9 Inquire about an Open NetCDF Dataset: nc_inq Family


Members of the nc_inq family of functions return information about an open netCDF dataset, given its netCDF ID. Dataset inquire functions may be called from either define mode or data mode. The first function, nc_inq, returns values for the number of dimensions, the number of variables, the number of global attributes, and the dimension ID of the dimension defined with unlimited length, if any. The other functions in the family each return just one of these items of information.

For C, these functions include nc_inq, nc_inq_ndims, nc_inq_nvars, nc_inq_natts, and nc_inq_unlimdim.

No I/O is performed when these functions are called, since the required information is available in memory for each open netCDF dataset.

Usage

int nc_inq          (int ncid, int *ndimsp, int *nvarsp, int *ngattsp,
                     int *unlimdimidp);
int nc_inq_ndims    (int ncid, int *ndimsp);
int nc_inq_nvars    (int ncid, int *nvarsp);
int nc_inq_natts    (int ncid, int *ngattsp);
int nc_inq_unlimdim (int ncid, int *unlimdimidp);
ncidNetCDF ID, from a previous call to nc_open or nc_create.
ndimspPointer to location for returned number of dimensions defined for this netCDF dataset.
nvarspPointer to location for returned number of variables defined for this netCDF dataset.
ngattspPointer to location for returned number of global attributes defined for this netCDF dataset.
unlimdimidpPointer to location for returned ID of the unlimited dimension, if there is one for this netCDF dataset. If no unlimited length dimension has been defined, -1 is returned.
Errors

All members of the nc_inq family return the value NC_NOERR if no errors occurred. Otherwise, the returned status indicates an error. Possible causes of errors include:

Example

Here is an example using nc_inq to find out about a netCDF dataset named foo.nc:

#include <netcdf.h>
   ... 
int status, ncid, ndims, nvars, ngatts, unlimdimid;
   ... 
status = nc_open("foo.nc", NC_NOWRITE, &ncid);
if (status != NC_NOERR) handle_error(status);
   ... 
status = nc_inq(ncid, &ndims, &nvars, &ngatts, &unlimdimid);
if (status != NC_NOERR) handle_error(status);

5.10 Synchronize an Open NetCDF Dataset to Disk: nc_sync


The function nc_sync offers a way to synchronize the disk copy of a netCDF dataset with in-memory buffers. There are two reasons you might want to synchronize after writes:

This function is backward-compatible with previous versions of the netCDF library. The intent was to allow sharing of a netCDF dataset among multiple readers and one writer, by having the writer call nc_sync after writing and the readers call nc_sync before each read. For a writer, this flushes buffers to disk. For a reader, it makes sure that the next read will be from disk rather than from previously cached buffers, so that the reader will see changes made by the writing process (e.g., the number of records written) without having to close and reopen the dataset. If you are only accessing a small amount of data, it can be expensive in computer resources to always synchronize to disk after every write, since you are giving up the benefits of buffering.

An easier way to accomplish sharing (and what is now recommended) is to have the writer and readers open the dataset with the NC_SHARE flag, and then it will not be necessary to call nc_sync at all. However, the nc_sync function still provides finer granularity than the NC_SHARE flag, if only a few netCDF accesses need to be synchronized among processes.

It is important to note that changes to the ancillary data, such as attribute values, are not propagated automatically by use of the NC_SHARE flag. Use of the nc_sync function is still required for this purpose.

Sharing datasets when the writer enters define mode to change the data schema requires extra care. In previous releases, after the writer left define mode, the readers were left looking at an old copy of the dataset, since the changes were made to a new copy. The only way readers could see the changes was by closing and reopening the dataset. Now the changes are made in place, but readers have no knowledge that their internal tables are now inconsistent with the new dataset schema. If netCDF datasets are shared across redefinition, some mechanism external to the netCDF library must be provided that prevents access by readers during redefinition and causes the readers to call nc_sync before any subsequent access.

When calling nc_sync, the netCDF dataset must be in data mode. A netCDF dataset in define mode is synchronized to disk only when nc_enddef is called. A process that is reading a netCDF dataset that another process is writing may call nc_sync to get updated with the changes made to the data by the writing process (e.g., the number of records written), without having to close and reopen the dataset.

Data is automatically synchronized to disk when a netCDF dataset is closed, or whenever you leave define mode.

Usage

int nc_sync(int ncid);
ncidNetCDF ID, from a previous call to nc_open or nc_create.
Errors

nc_sync returns the value NC_NOERR if no errors occurred. Otherwise, the returned status indicates an error. Possible causes of errors include:

Example

Here is an example using nc_sync to synchronize the disk writes of a netCDF dataset named foo.nc:

#include <netcdf.h>
   ... 
int status;
int ncid;
   ... 
status = nc_open("foo.nc", NC_WRITE, &ncid);  /* open for writing */
if (status != NC_NOERR) handle_error(status);

   ...           /* write data or change attributes */

status = nc_sync(ncid);      /* synchronize to disk */
if (status != NC_NOERR) handle_error(status);

5.11 Back Out of Recent Definitions: nc_abort


You no longer need to call this function, since it is called automatically by nc_close in case the dataset is in define mode and something goes wrong with committing the changes. The function nc_abort just closes the netCDF dataset, if not in define mode. If the dataset is being created and is still in define mode, the dataset is deleted. If define mode was entered by a call to nc_redef, the netCDF dataset is restored to its state before definition mode was entered and the dataset is closed.

Usage

int nc_abort(int ncid);
ncidNetCDF ID, from a previous call to nc_open or nc_create.
Errors

nc_abort returns the value NC_NOERR if no errors occurred. Otherwise, the returned status indicates an error. Possible causes of errors include:

Example

Here is an example using nc_abort to back out of redefinitions of a dataset named foo.nc:

#include <netcdf.h>
   ... 
int ncid, status, latid;
   ... 
status = nc_open("foo.nc", NC_WRITE, &ncid);/* open for writing */
if (status != NC_NOERR) handle_error(status);
   ... 
status = nc_redef(ncid);                    /* enter define mode */
if (status != NC_NOERR) handle_error(status);
   ... 
status = nc_def_dim(ncid, "lat", 18L, &latid);
if (status != NC_NOERR) {
   handle_error(status);
   status = nc_abort(ncid);                 /* define failed, abort */
   if (status != NC_NOERR) handle_error(status);
}

5.12 Set Fill Mode for Writes: nc_set_fill


This function is intended for advanced usage, to optimize writes under some circumstances described below. The function nc_set_fill sets the fill mode for a netCDF dataset open for writing and returns the current fill mode in a return parameter. The fill mode can be specified as either NC_FILL or NC_NOFILL. The default behavior corresponding to NC_FILL is that data is pre-filled with fill values, that is fill values are written when you create non-record variables or when you write a value beyond data that has not yet been written. This makes it possible to detect attempts to read data before it was written. See Section 7.16 "Fill Values," page 78, for more information on the use of fill values. See Section 8.1 "Attribute Conventions," page 81, for information about how to define your own fill values.

The behavior corresponding to NC_NOFILL overrides the default behavior of prefilling data with fill values. This can be used to enhance performance, because it avoids the duplicate writes that occur when the netCDF library writes fill values that are later overwritten with data.

A value indicating which mode the netCDF dataset was already in is returned. You can use this value to temporarily change the fill mode of an open netCDF dataset and then restore it to the previous mode.

After you turn on NC_NOFILL mode for an open netCDF dataset, you must be certain to write valid data in all the positions that will later be read. Note that nofill mode is only a transient property of a netCDF dataset open for writing: if you close and reopen the dataset, it will revert to the default behavior. You can also revert to the default behavior by calling nc_set_fill again to explicitly set the fill mode to NC_FILL.

There are three situations where it is advantageous to set nofill mode:

1. Creating and initializing a netCDF dataset. In this case, you should set nofill mode before calling nc_enddef and then write completely all non-record variables and the initial records of all the record variables you want to initialize.

2. Extending an existing record-oriented netCDF dataset. Set nofill mode after opening the dataset for writing, then append the additional records to the dataset completely, leaving no intervening unwritten records.

3. Adding new variables that you are going to initialize to an existing netCDF dataset. Set nofill mode before calling nc_enddef then write all the new variables completely.

If the netCDF dataset has an unlimited dimension and the last record was written while in nofill mode, then the dataset may be shorter than if nofill mode was not set, but this will be completely transparent if you access the data only through the netCDF interfaces.

The use of this feature may not be available (or even needed) in future releases. Programmers are cautioned against heavy reliance upon this feature.

Usage

int nc_set_fill (int ncid, int fillmode, int *old_modep];
ncidNetCDF ID, from a previous call to nc_open or nc_create.
fillmodeDesired fill mode for the dataset, either NC_NOFILL or NC_FILL.
old_modepPointer to location for returned current fill mode of the dataset before this call, either NC_NOFILL or NC_FILL.
Errors

nc_set_fill returns the value NC_NOERR if no errors occurred. Otherwise, the returned status indicates an error. Possible causes of errors include:

Example The fill mode argument is neither NC_NOFILL nor NC_FILL.

Here is an example using nc_set_fill to set nofill mode for subsequent writes of a netCDF dataset named foo.nc:

#include <netcdf.h>
   ... 
int ncid, status, old_fill_mode;
   ... 
status = nc_open("foo.nc", NC_WRITE, &ncid);  /* open for writing */
if (status != NC_NOERR) handle_error(status);

   ...           /* write data with default prefilling behavior */

status = nc_set_fill(ncid, NC_NOFILL, &old_fill_mode); /* set nofill */
if (status != NC_NOERR) handle_error(status);

   ...           /* write data with no prefilling */
5.1 - NetCDF Library Interface Descriptions
5.2 - Get error message corresponding to error status: nc_strerror
Usage -
Example -
5.3 - Get netCDF library version: nc_inq_libvers
Usage -
Example -
5.4 - Create a NetCDF dataset: nc_create
Usage -
Example -
5.5 - Open a NetCDF Dataset for Access: nc_open
Usage -
Example -
5.6 - Put Open NetCDF Dataset into Define Mode: nc_redef
Usage -
Example -
5.7 - Leave Define Mode: nc_enddef
Usage -
Example -
5.8 - Close an Open NetCDF Dataset: nc_close
Usage -
Example -
5.9 - Inquire about an Open NetCDF Dataset: nc_inq Family
Usage -
Example -
5.10 - Synchronize an Open NetCDF Dataset to Disk: nc_sync
Usage -
Example -
5.11 - Back Out of Recent Definitions: nc_abort
Usage -
Example -
5.12 - Set Fill Mode for Writes: nc_set_fill
Usage -
Example - The fill mode argument is neither NC_NOFILL nor NC_FILL.

NetCDF User's Guide for C - 5 JUN 1997
[Next] [Previous] [Top] [Contents] [Index] [netCDF Home Page][Unidata Home Page]