NetCDF C Interface Guide
NetCDF C Interface Guide
discussions, stats, and author profiles for this publication at: https://www.researchgate.net/publication/266186479
Article
CITATIONS READS
2 108
4 authors, including:
Russ Rew
University Consortium for Atmospheric Research
23 PUBLICATIONS 640 CITATIONS
SEE PROFILE
Some of the authors of this publication are also working on these related projects:
All content following this page was uploaded by Russ Rew on 27 November 2014.
Permission is granted to make and distribute verbatim copies of this manual provided that
the copyright notice and these paragraphs are preserved on all copies. The software and any
accompanying written materials are provided “as is” without warranty of any kind. UCAR
expressly disclaims all warranties of any kind, either expressed or implied, including but not
limited to the implied warranties of merchantability and fitness for a particular purpose.
The Unidata Program Center is managed by the University Corporation for Atmospheric
Research and sponsored by the National Science Foundation. Any opinions, findings, con-
clusions, or recommendations expressed in this publication are those of the author(s) and
do not necessarily reflect the views of the National Science Foundation.
Mention of any commercial company or product in this document does not constitute an
endorsement by the Unidata Program Center. Unidata does not authorize any use of
information from this publication for advertising or publicity purposes.
i
Table of Contents
2 Datasets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.1 NetCDF Library Interface Descriptions . . . . . . . . . . . . . . . . . . . . . . . 9
2.2 Get error message corresponding to error status: nc strerror . . . 10
2.3 Get netCDF library version: nc inq libvers . . . . . . . . . . . . . . . . . . . 10
2.4 Create a NetCDF Dataset: nc create . . . . . . . . . . . . . . . . . . . . . . . . 11
2.5 Create a NetCDF Dataset With Performance Options: nc create
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.6 Open a NetCDF Dataset for Access: nc open. . . . . . . . . . . . . . . . . 16
2.7 Open a NetCDF Dataset for Access with Performance Tuning:
nc open . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.8 Put Open NetCDF Dataset into Define Mode: nc redef . . . . . . . 18
2.9 Leave Define Mode: nc enddef . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.10 Leave Define Mode with Performance Tuning: nc enddef . . . . 20
2.11 Close an Open NetCDF Dataset: nc close . . . . . . . . . . . . . . . . . . . 21
2.12 Inquire about an Open NetCDF Dataset: nc inq Family. . . . . . 22
2.13 Synchronize an Open NetCDF Dataset to Disk: nc sync . . . . . 23
2.14 Back Out of Recent Definitions: nc abort . . . . . . . . . . . . . . . . . . . 25
2.15 Set Fill Mode for Writes: nc set fill . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.16 Set Default Creation Format: nc set default format . . . . . . . . . 27
3 Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.1 Dimensions Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2 Create a Dimension: nc def dim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.3 Get a Dimension ID from Its Name: nc inq dimid . . . . . . . . . . . . 32
3.4 Inquire about a Dimension: nc inq dim Family . . . . . . . . . . . . . . . 33
3.5 Rename a Dimension: nc rename dim . . . . . . . . . . . . . . . . . . . . . . . 34
4 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.2 Language Types Corresponding to netCDF external data types
........................................................... 37
4.3 Create a Variable: nc_def_var . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
4.4 Get a Variable ID from Its Name: nc inq varid . . . . . . . . . . . . . . . 40
4.5 Get Information about a Variable from Its ID: nc inq var . . . . . 40
ii NetCDF C Interface Guide
5 Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
5.2 Create an Attribute: nc put att type . . . . . . . . . . . . . . . . . . . . . . . 69
5.3 Get Information about an Attribute: nc inq att Family . . . . . . . 71
5.4 Get Attribute’s Values:nc get att type . . . . . . . . . . . . . . . . . . . . . . 73
5.5 Copy Attribute from One NetCDF to Another: nc copy att . . . 75
5.6 Rename an Attribute: nc rename att . . . . . . . . . . . . . . . . . . . . . . . . 76
5.7 Delete an Attribute: nc del att . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
1
This document describes the C interface to the netCDF library. This document applies
to netCDF version 3.6.0. This document was last updated in December 2004.
For a complete description of the netCDF format and utilities see section “Top” in The
NetCDF Users’ Guide.
2 NetCDF C Interface Guide
Chapter 1: Use of the NetCDF Library 3
variable may be written at once with one of the members of the nc put var family. Arrays
or array cross-sections of a variable may be written using members of the nc put vara fam-
ily. Subsampled array sections may be written using members of the nc put vars family.
Mapped array sections may be written using members of the nc put varm family. (Sub-
sampled and mapped access are general forms of data access that are explained later.)
Finally, you should explicitly close all netCDF datasets that have been opened for writing
by calling nc close. By default, access to the file system is buffered by the netCDF library.
If a program terminates abnormally with netCDF datasets open for writing, your most
recent modifications may be lost. This default buffering of data is disabled by setting the
NC SHARE flag when opening the dataset. But even if this flag is set, changes to attribute
values or changes made in define mode are not written out until nc sync or nc close is
called.
Once the IDs and shapes of netCDF variables are known, data values can be accessed by
calling a member of the nc get var1 family for single values, or members of the nc get var,
nc get vara, nc get vars, or nc get varm for various kinds of array access.
some means external to the library is necessary to prevent readers from making concurrent
accesses and to inform readers to call nc sync before the next access.
2 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:
• Get version of library.
• Get error message corresponding to a returned error code.
The operations supported on a netCDF dataset as a single object are:
• Create, given dataset name and whether to overwrite or not.
• Open for access, given dataset name and read or write intent.
• Put into define mode, to add dimensions, variables, or attributes.
• Take out of define mode, checking consistency of additions.
• Close, writing to disk if required.
• Inquire about the number of dimensions, number of variables, number of global at-
tributes, and ID of the unlimited dimension, if any.
• Synchronize to disk to make sure it is current.
• Set and unset nofill mode for optimized sequential writes.
• 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.
Usage
const char * nc_strerror(int ncerr);
ncerr An 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);
}
}
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:
Chapter 2: Datasets 11
#include <netcdf.h>
...
printf("%s\n", nc_inq_libvers());
Usage
int nc_create (const char* path, int cmode, int *ncidp);
path The file name of the new netCDF dataset.
cmode The creation mode flag. The following flags are available: NC NOCLOBBER,
NC SHARE, and NC 64BIT OFFSET.
Setting NC NOCLOBBER 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 optimized for sequential access, programs that do not ac-
cess data sequentially may see some performance improvement by setting the
NC SHARE flag.
Setting NC 64BIT OFFSET causes netCDF to create a 64-bit offset format file,
instead of a netCDF classic format file. The 64-bit offset format imposes far
fewer restrictions on very large (i.e. over 2 GB) data files. See section “Large
File Support” in The NetCDF Users’ Guide.
A zero value (defined for convenience as NC CLOBBER) specifies the default
behavior: overwrite any existing dataset with the same file name and buffer and
cache accesses for efficiency. The dataset will be in netCDF classic format. See
section “NetCDF Classic Format Limitations” in The NetCDF Users’ Guide.
ncidp Pointer 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:
12 NetCDF C Interface Guide
• Passing a dataset name that includes a directory that does not exist.
• Specifying a dataset name of a file that exists and also specifying NC NOCLOBBER.
• Specifying a meaningless value for the creation mode.
• Attempting to create a netCDF dataset in a directory where you don’t have permission
to create files.
Examples
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);
In this example we create a netCDF dataset named foo large.nc. It will be in the 64-bit
offset format.
#include <netcdf.h>
...
int status;
int ncid;
...
status = nc_create("foo.nc", NC_NOCLOBBER, &ncid);
if (status != NC_NOERR) handle_error(status);
A variant of nc create, nc create (note the double underscore) allows users to specify
two tuning parameters for the file that it is creating. These tuning parameters are not
written to the data file, they are only used for so long as the file remains open after an
nc create.
Usage
int nc__create(const char *path, int cmode, size_t initialsz,
size_t *chunksizehintp, int *ncidp);
path The file name of the new netCDF dataset.
cmode The creation mode flag. The following flags are available: NC NOCLOBBER,
NC SHARE, and NC 64BIT OFFSET.
Setting NC NOCLOBBER 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
Chapter 2: Datasets 13
buffering scheme is optimized for sequential access, programs that do not ac-
cess data sequentially may see some performance improvement by setting the
NC SHARE flag.
Setting NC 64BIT OFFSET causes netCDF to create a 64-bit offset format file,
instead of a netCDF classic format file. The 64-bit offset format imposes far
fewer restrictions on very large (i.e. over 2 GB) data files. See section “Large
File Support” in The NetCDF Users’ Guide.
A zero value (defined for convenience as NC CLOBBER) specifies the default
behavior: overwrite any existing dataset with the same file name and buffer and
cache accesses for efficiency. The dataset will be in netCDF classic format. See
section “NetCDF Classic Format Limitations” in The NetCDF Users’ Guide.
initialsz
On some systems, and with custom I/O layers, it may be advantageous to set
the size of the output file at creation time. This parameter sets the initial size
of the file at creation time.
chunksizehintp
The argument referenced by chunksizehintp controls a space versus time trade-
off, memory allocated in the netcdf library versus number of system calls.
Because of internal requirements, the value may not be set to exactly the value
requested. The actual value chosen is returned by reference.
Using the value NC SIZEHINT DEFAULT causes the library to choose a de-
fault. How the system chooses the default depends on the system. On many
systems, the "preferred I/O block size" is available from the stat() system call,
struct stat member st blksize. If this is available it is used. Lacking that, twice
the system pagesize is used.
Lacking a call to discover the system pagesize, we just set default chunksize to
8192.
The chunksize is a property of a given open netcdf descriptor ncid, it is not a
persistent property of the netcdf dataset.
ncidp Pointer 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:
• Passing a dataset name that includes a directory that does not exist.
• Specifying a dataset name of a file that exists and also specifying NC NOCLOBBER.
• Specifying a meaningless value for the creation mode.
• Attempting to create a netCDF dataset in a directory where you don’t have permission
to create files.
Examples
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:
14 NetCDF C Interface Guide
#include <netcdf.h>
...
int status;
int ncid;
...
status = nc_create("foo.nc", NC_NOCLOBBER, &ncid);
if (status != NC_NOERR) handle_error(status);
In this example we create a netCDF dataset named foo large.nc. It will be in the 64-bit
offset format.
#include <netcdf.h>
...
int status;
int ncid;
...
status = nc_create("foo.nc", NC_NOCLOBBER, &ncid);
if (status != NC_NOERR) handle_error(status);
Usage
int nc__create(const char *path, int cmode, size_t initialsz,
size_t *chunksizehintp, int *ncidp);
path The file name of the new netCDF dataset.
cmode The creation mode flag. The following flags are available: NC NOCLOBBER,
NC SHARE, and NC 64BIT OFFSET.
Setting NC NOCLOBBER 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
Chapter 2: Datasets 15
buffering scheme is optimized for sequential access, programs that do not ac-
cess data sequentially may see some performance improvement by setting the
NC SHARE flag.
Setting NC 64BIT OFFSET causes netCDF to create a 64-bit offset format file,
instead of a netCDF classic format file. The 64-bit offset format imposes far
fewer restrictions on very large (i.e. over 2 GB) data files. See section “Large
File Support” in The NetCDF Users’ Guide.
A zero value (defined for convenience as NC CLOBBER) specifies the default
behavior: overwrite any existing dataset with the same file name and buffer and
cache accesses for efficiency. The dataset will be in netCDF classic format. See
section “NetCDF Classic Format Limitations” in The NetCDF Users’ Guide.
initialsz
This parameter sets the initial size of the file at creation time.
chunksizehintp
The argument referenced by chunksizehintp controls a space versus time trade-
off, memory allocated in the netcdf library versus number of system calls.
Because of internal requirements, the value may not be set to exactly the value
requested. The actual value chosen is returned by reference.
Using the value NC SIZEHINT DEFAULT causes the library to choose a de-
fault. How the system chooses the default depends on the system. On many
systems, the "preferred I/O block size" is available from the stat() system call,
struct stat member st blksize. If this is available it is used. Lacking that, twice
the system pagesize is used.
Lacking a call to discover the system pagesize, we just set default chunksize to
8192.
The chunksize is a property of a given open netcdf descriptor ncid, it is not a
persistent property of the netcdf dataset.
ncidp Pointer 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:
• Passing a dataset name that includes a directory that does not exist.
• Specifying a dataset name of a file that exists and also specifying NC NOCLOBBER.
• Specifying a meaningless value for the creation mode.
• Attempting to create a netCDF dataset in a directory where you don’t have permission
to create files.
Examples
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.
We also specify that chunksize and initial size for the file.
16 NetCDF C Interface Guide
#include <netcdf.h>
...
int status;
int ncid;
int intialsz = 2048;
int *chunksize;
...
*chunksize = 1024;
status = nc__create("foo.nc", NC_NOCLOBBER, initialsz, chunksize, &ncid);
if (status != NC_NOERR) handle_error(status);
Usage
int nc_open (const char *path, int omode, int *ncidp);
path File name for netCDF dataset to be opened.
omode A 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
optimized for sequential access, programs that do not access data sequentially
may see some performance improvement by setting the NC SHARE flag.
ncidp Pointer 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:
• The specified netCDF dataset does not exist.
• A meaningless mode was specified.
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>
...
Chapter 2: Datasets 17
int status;
int ncid;
...
status = nc_open("foo.nc", 0, &ncid);
if (status != NC_NOERR) handle_error(status);
Usage
int nc__open(const char *path, int mode, size_t *chunksizehintp, int *ncidp);
Errors
nc open returns the value NC NOERR if no errors occurred. Otherwise, the returned
status indicates an error. Possible causes of errors include:
• The specified netCDF dataset does not exist.
• A meaningless mode was specified.
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;
int *chunksize;
...
*chunksize = 1024;
status = nc_open("foo.nc", 0, chunksize, &ncid);
if (status != NC_NOERR) handle_error(status);
Usage
int nc_redef(int ncid);
ncid netCDF 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:
• The specified netCDF dataset is already in define mode.
• The specified netCDF dataset was opened for read-only.
• The specified netCDF ID does not refer to an open netCDF dataset.
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;
...
Chapter 2: Datasets 19
Usage
int nc_enddef(int ncid);
ncid NetCDF 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:
• The specified netCDF dataset is not in define mode.
• The specified netCDF ID does not refer to an open netCDF dataset.
• The size of one or more variables exceed the size constraints for whichever variant of
the file format is in use). See section “Large File Support” in The NetCDF Users’
Guide.
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);
Usage
int nc__enddef(int ncid, size_t h_minfree, size_t v_align,
size_t v_minfree, size_t r_align);
ncid NetCDF ID, from a previous call to nc open or nc create.
h_minfree
Sets the pad at the end of the "header" section.
Chapter 2: Datasets 21
v_align Controls the alignment of the beginning of the data section for fixed size vari-
ables.
v_minfree
Sets the pad at the end of the data section for fixed size variables.
r_align Controls the alignment of the beginning of the data section for variables which
have an unlimited dimension (record variables).
Errors
nc enddef returns the value NC NOERR if no errors occurred. Otherwise, the returned
status indicates an error. Possible causes of errors include:
• The specified netCDF dataset is not in define mode.
• The specified netCDF ID does not refer to an open netCDF dataset.
• The size of one or more variables exceed the size constraints for whichever variant of
the file format is in use). See section “Large File Support” in The NetCDF Users’
Guide.
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);
Usage
int nc_close(int ncid);
ncid NetCDF ID, from a previous call to nc open or nc create.
22 NetCDF C Interface Guide
Errors
nc close returns the value NC NOERR if no errors occurred. Otherwise, the returned status
indicates an error. Possible causes of errors include:
• Define mode was entered and the automatic call made to nc enddef failed.
• The specified netCDF ID does not refer to an open netCDF dataset.
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);
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);
ncid NetCDF ID, from a previous call to nc open or nc create.
Chapter 2: Datasets 23
ndimsp Pointer to location for returned number of dimensions defined for this netCDF
dataset.
nvarsp Pointer to location for returned number of variables defined for this netCDF
dataset.
ngattsp Pointer to location for returned number of global attributes defined for this
netCDF dataset.
unlimdimidp
Pointer 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. Oth-
erwise, the returned status indicates an error. Possible causes of errors include:
• The specified netCDF ID does not refer to an open netCDF dataset.
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);
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);
ncid NetCDF 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:
• The netCDF dataset is in define mode.
• The specified netCDF ID does not refer to an open netCDF dataset.
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;
Chapter 2: Datasets 25
int ncid;
...
status = nc_open("foo.nc", NC_WRITE, &ncid); /* open for writing */
if (status != NC_NOERR) handle_error(status);
Usage
int nc_abort(int ncid);
ncid NetCDF 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:
• When called from define mode while creating a netCDF dataset, deletion of the dataset
failed.
• The specified netCDF ID does not refer to an open netCDF dataset.
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) {
26 NetCDF C Interface Guide
handle_error(status);
status = nc_abort(ncid); /* define failed, abort */
if (status != NC_NOERR) handle_error(status);
}
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. Pro-
grammers are cautioned against heavy reliance upon this feature.
Chapter 2: Datasets 27
Usage
int nc_set_fill (int ncid, int fillmode, int *old_modep);
ncid NetCDF ID, from a previous call to nc open or nc create.
fillmode Desired fill mode for the dataset, either NC NOFILL or NC FILL.
old_modep
Pointer 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:
• The specified netCDF ID does not refer to an open netCDF dataset.
• The specified netCDF ID refers to a dataset open for read-only access.
• The fill mode argument is neither NC NOFILL nor NC FILL..
Example
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);
Users who do what to use 64-bit offset format files can create them directory from
nc create, using the proper cmode flag. (see Section 2.4 [nc create], page 11).
The function nc set default format allows the user to change the format of the netCDF
file to be created by future calls to nc create (or nc create) without changing the cmode
flag.
This allows the user to convert a program to use 64-bit offset formation without changing
all calls the nc create. See section “Large File Support” in The NetCDF Users’ Guide.
Once the default format is set, all future created files will be in the desired format.
Two constants are provided in the netcdf.h file to be used with this function,
NC FORMAT 64BIT and NC FORMAT CLASSIC.
If a non-NULL pointer is provided, it is assumed to point to an int, where the existing
default format will be written.
Using nc create with a cmode including NC 64BIT OFFSET overrides the default for-
mat, and creates a 64-bit offset file.
Usage
int nc_set_default_format(int format, int *old_formatp);
format Either NC FORMAT CLASSIC (the default setting) or NC FORMAT 64BIT.
old_formatp
Either NULL (in which case it will be ignored), or a pointer to an int where
the existing default format (i.e. before being changed to the new format) will
be written. This allows you to get the existing default format while setting a
new default format.
Errors
nc set default format returns the value NC NOERR if no errors occurred. Otherwise, the
returned status indicates an error. Possible causes of errors include:
• Invalid format. The only valid formats are NC FORMAT CLASSIC and
NC FORMAT 64BIT. Trying to set the default format to something else will result
in an invalid argument error. (NC EINVAL)
Example
Here is an example using nc set default format to create the same file in both formats with
the same nc create call:
#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);
3 Dimensions
Usage
int nc_def_dim (int ncid, const char *name, size_t len, int *dimidp);
ncid NetCDF ID, from a previous call to nc open or nc create.
32 NetCDF C Interface Guide
name Dimension name. Must begin with an alphabetic character, followed by zero or
more alphanumeric characters including the underscore (’ ’). Case is significant.
len Length of dimension; that is, number of values for this dimension as an index
to variables that use it. This should be either a positive integer (of type size t)
or the predefined constant NC UNLIMITED.
dimidp Pointer to location for returned dimension ID.
Errors
nc def dim returns the value NC NOERR if no errors occurred. Otherwise, the returned
status indicates an error. Possible causes of errors include:
• The netCDF dataset is not in definition mode.
• The specified dimension name is the name of another existing dimension.
• The specified length is not greater than zero.
• The specified length is unlimited, but there is already an unlimited length dimension
defined for this netCDF dataset.
• The specified netCDF ID does not refer to an open netCDF dataset.
Example
Here is an example using nc def dim to create a dimension named lat of length 18 and a
unlimited dimension named rec in a new netCDF dataset named foo.nc:
#include <netcdf.h>
...
int status, ncid, latid, recid;
...
status = nc_create("foo.nc", NC_NOCLOBBER, &ncid);
if (status != NC_NOERR) handle_error(status);
...
status = nc_def_dim(ncid, "lat", 18L, &latid);
if (status != NC_NOERR) handle_error(status);
status = nc_def_dim(ncid, "rec", NC_UNLIMITED, &recid);
if (status != NC_NOERR) handle_error(status);
Usage
int nc inq dimid (int ncid, const char *name, int *dimidp);
ncid NetCDF ID, from a previous call to nc open or nc create.
name Dimension name, a character string beginning with a letter and followed by any
sequence of letters, digits, or underscore (’ ’) characters. Case is significant in
dimension names.
Chapter 3: Dimensions 33
Errors
nc inq dimid returns the value NC NOERR if no errors occurred. Otherwise, the returned
status indicates an error. Possible causes of errors include:
The name that was specified is not the name of a dimension in the netCDF dataset. The
specified netCDF ID does not refer to an open netCDF dataset.
Example
Here is an example using nc inq dimid to determine the dimension ID of a dimension named
lat, assumed to have been defined previously in an existing netCDF dataset named foo.nc:
#include <netcdf.h>
...
int status, ncid, latid;
...
status = nc_open("foo.nc", NC_NOWRITE, &ncid); /* open for reading */
if (status != NC_NOERR) handle_error(status);
...
status = nc_inq_dimid(ncid, "lat", &latid);
if (status != NC_NOERR) handle_error(status);
Usage
int nc_inq_dim (int ncid, int dimid, char* name, size_t* lengthp);
int nc_inq_dimname (int ncid, int dimid, char *name);
int nc_inq_dimlen (int ncid, int dimid, size_t *lengthp);
ncid NetCDF ID, from a previous call to nc open or nc create.
dimid Dimension ID, from a previous call to nc inq dimid or nc def dim.
name Returned dimension name. The caller must allocate space for the returned
name. The maximum possible length, in characters, of a dimension name is
given by the predefined constant NC MAX NAME. (This doesn’t include the
null terminator, so declare your array to be size NC MAX NAME+1). The
returned character array will be null-terminated.
lengthp Pointer to location for returned length of dimension. For the unlimited dimen-
sion, this is the number of records written so far.
34 NetCDF C Interface Guide
Errors
These functions return the value NC NOERR if no errors occurred. Otherwise, the returned
status indicates an error. Possible causes of errors include:
• The dimension ID is invalid for the specified netCDF dataset.
• The specified netCDF ID does not refer to an open netCDF dataset.
Example
Here is an example using nc inq dim to determine the length of a dimension named lat, and
the name and current maximum length of the unlimited dimension for an existing netCDF
dataset named foo.nc:
#include <netcdf.h>
...
int status, ncid, latid, recid;
size_t latlength, recs;
char recname[NC_MAX_NAME+1];
...
status = nc_open("foo.nc", NC_NOWRITE, &ncid); /* open for reading */
if (status != NC_NOERR) handle_error(status);
status = nc_inq_unlimdim(ncid, &recid); /* get ID of unlimited dimension */
if (status != NC_NOERR) handle_error(status);
...
status = nc_inq_dimid(ncid, "lat", &latid); /* get ID for lat dimension */
if (status != NC_NOERR) handle_error(status);
status = nc_inq_dimlen(ncid, latid, &latlength); /* get lat length */
if (status != NC_NOERR) handle_error(status);
/* get unlimited dimension name and current length */
status = nc_inq_dim(ncid, recid, recname, &recs);
if (status != NC_NOERR) handle_error(status);
Usage
int nc rename dim(int ncid, int dimid, const char* name);
ncid NetCDF ID, from a previous call to nc open or nc create.
dimid Dimension ID, from a previous call to nc inq dimid or nc def dim.
name New dimension name.
Errors
nc rename dim returns the value NC NOERR if no errors occurred. Otherwise, the re-
turned status indicates an error. Possible causes of errors include:
Chapter 3: Dimensions 35
Example
Here is an example using nc rename dim to rename the dimension lat to latitude in an
existing netCDF dataset named foo.nc:
#include <netcdf.h>
...
int status, ncid, latid;
...
status = nc_open("foo.nc", NC_WRITE, &ncid); /* open for writing */
if (status != NC_NOERR) handle_error(status);
...
status = nc_redef(ncid); /* put in define mode to rename dimension */
if (status != NC_NOERR) handle_error(status);
status = nc_inq_dimid(ncid, "lat", &latid);
if (status != NC_NOERR) handle_error(status);
status = nc_rename_dim(ncid, latid, "latitude");
if (status != NC_NOERR) handle_error(status);
status = nc_enddef(ncid); /* leave define mode */
if (status != NC_NOERR) handle_error(status);
36 NetCDF C Interface Guide
Chapter 4: Variables 37
4 Variables
4.1 Introduction
Variables for a netCDF dataset are defined when the dataset is created, while the netCDF
dataset is in define mode. Other variables may be added later by reentering define mode.
A netCDF variable has a name, a type, and a shape, which are specified when it is defined.
A variable may also have values, which are established later in data mode.
Ordinarily, the name, type, and shape are fixed when the variable is first defined. The
name may be changed, but the type and shape of a variable cannot be changed. However,
a variable defined in terms of the unlimited dimension can grow without bound in that
dimension.
A netCDF variable in an open netCDF dataset is referred to by a small integer called a
variable ID.
Variable IDs reflect the order in which variables were defined within a netCDF dataset.
Variable IDs are 0, 1, 2,..., in the order in which the variables were defined. A function is
available for getting the variable ID from the variable name and vice-versa.
Attributes (see Chapter 5 [Attributes], page 69) may be associated with a variable to
specify such properties as units.
Operations supported on variables are:
• Create a variable, given its name, data type, and shape.
• Get a variable ID from its name.
• Get a variable’s name, data type, shape, and number of attributes from its ID.
• Put a data value into a variable, given variable ID, indices, and value.
• Put an array of values into a variable, given variable ID, corner indices, edge lengths,
and a block of values.
• Put a subsampled or mapped array-section of values into a variable, given variable ID,
corner indices, edge lengths, stride vector, index mapping vector, and a block of values.
• Get a data value from a variable, given variable ID and indices.
• Get an array of values from a variable, given variable ID, corner indices, and edge
lengths.
• Get a subsampled or mapped array-section of values from a variable, given variable ID,
corner indices, edge lengths, stride vector, and index mapping vector.
• Rename a variable.
byte NC BYTE 8
38 NetCDF C Interface Guide
char NC CHAR 8
short NC SHORT 16
int NC INT 32
float NC FLOAT 32
double NC DOUBLE 64
The first column gives the netCDF external data type, which is the same as the CDL data
type. The next column gives the corresponding C preprocessor macro for use in netCDF
functions (the preprocessor macros are defined in the netCDF C header-file netcdf.h). The
last column gives the number of bits used in the external representation of values of the
corresponding type.
Note that there are no netCDF types corresponding to 64-bit integers or to characters
wider than 8 bits in the current version of the netCDF library.
Usage
int nc_def_var (int ncid, const char *name, nc_type xtype,
int ndims, const int dimids[], int *varidp);
name Variable name. Must begin with an alphabetic character, followed by zero or
more alphanumeric characters including the underscore (’ ’). Case is significant.
xtype One of the set of predefined netCDF external data types. The type of this pa-
rameter, nc type, is defined in the netCDF header file. The valid netCDF exter-
nal data types are NC BYTE, NC CHAR, NC SHORT, NC INT, NC FLOAT,
and NC DOUBLE.
ndims Number of dimensions for the variable. For example, 2 specifies a matrix, 1
specifies a vector, and 0 means the variable is a scalar with no dimensions. Must
not be negative or greater than the predefined constant NC MAX VAR DIMS.
dimids Vector of ndims dimension IDs corresponding to the variable dimensions. If the
ID of the unlimited dimension is included, it must be first. This argument is
ignored if ndims is 0.
Errors
nc def var returns the value NC NOERR if no errors occurred. Otherwise, the returned
status indicates an error. Possible causes of errors include:
• The netCDF dataset is not in define mode.
• The specified variable name is the name of another existing variable.
• The specified type is not a valid netCDF type.
• The specified number of dimensions is negative or more than the constant
NC MAX VAR DIMS, the maximum number of dimensions permitted for a netCDF
variable.
• One or more of the dimension IDs in the list of dimensions is not a valid dimension ID
for the netCDF dataset.
• The number of variables would exceed the constant NC MAX VARS, the maximum
number of variables permitted in a netCDF dataset.
• The specified netCDF ID does not refer to an open netCDF dataset.
Example
Here is an example using nc def var to create a variable named rh of type double with three
dimensions, time, lat, and lon in a new netCDF dataset named foo.nc:
#include <netcdf.h>
...
int status; /* error status */
int ncid; /* netCDF ID */
int lat_dim, lon_dim, time_dim; /* dimension IDs */
int rh_id; /* variable ID */
int rh_dimids[3]; /* variable shape */
...
status = nc_create("foo.nc", NC_NOCLOBBER, &ncid);
if (status != NC_NOERR) handle_error(status);
...
/* define dimensions */
status = nc_def_dim(ncid, "lat", 5L, &lat_dim);
if (status != NC_NOERR) handle_error(status);
status = nc_def_dim(ncid, "lon", 10L, &lon_dim);
if (status != NC_NOERR) handle_error(status);
status = nc_def_dim(ncid, "time", NC_UNLIMITED, &time_dim);
if (status != NC_NOERR) handle_error(status);
...
/* define variable */
rh_dimids[0] = time_dim;
rh_dimids[1] = lat_dim;
rh_dimids[2] = lon_dim;
status = nc_def_var (ncid, "rh", NC_DOUBLE, 3, rh_dimids, &rh_id);
if (status != NC_NOERR) handle_error(status);
40 NetCDF C Interface Guide
Usage
int nc_inq_varid (int ncid, const char *name, int *varidp);
ncid NetCDF ID, from a previous call to nc open or nc create.
name Variable name for which ID is desired.
varidp Pointer to location for returned variable ID.
Errors
nc inq varid returns the value NC NOERR if no errors occurred. Otherwise, the returned
status indicates an error. Possible causes of errors include:
• The specified variable name is not a valid name for a variable in the specified netCDF
dataset.
• The specified netCDF ID does not refer to an open netCDF dataset.
Example
Here is an example using nc inq varid to find out the ID of a variable named rh in an
existing netCDF dataset named foo.nc:
#include <netcdf.h>
...
int status, ncid, rh_id;
...
status = nc_open("foo.nc", NC_NOWRITE, &ncid);
if (status != NC_NOERR) handle_error(status);
...
status = nc_inq_varid (ncid, "rh", &rh_id);
if (status != NC_NOERR) handle_error(status);
Usage
int nc_inq_var (int ncid, int varid, char *name, nc_type *xtypep,
int *ndimsp, int dimids[], int *nattsp);
int nc_inq_varname (int ncid, int varid, char *name);
int nc_inq_vartype (int ncid, int varid, nc_type *xtypep);
int nc_inq_varndims (int ncid, int varid, int *ndimsp);
int nc_inq_vardimid (int ncid, int varid, int dimids[]);
int nc_inq_varnatts (int ncid, int varid, int *nattsp);
ncid NetCDF ID, from a previous call to nc open or nc create.
varid Variable ID.
name Returned variable name. The caller must allocate space for the returned name.
The maximum possible length, in characters, of a variable name is given by
the predefined constant NC MAX NAME. (This doesn’t include the null ter-
minator, so declare your array to be size NC MAX NAME+1). The returned
character array will be null-terminated.
xtypep Pointer to location for returned variable type, one of the set of predefined
netCDF external data types. The type of this parameter, nc type, is defined in
the netCDF header file. The valid netCDF external data types are NC BYTE,
NC CHAR, NC SHORT, NC INT, NC FLOAT, and NC DOUBLE.
ndimsp Pointer to location for returned number of dimensions the variable was defined
as using. For example, 2 indicates a matrix, 1 indicates a vector, and 0 means
the variable is a scalar with no dimensions.
dimids Returned vector of *ndimsp dimension IDs corresponding to the variable dimen-
sions. The caller must allocate enough space for a vector of at least *ndimsp
integers to be returned. The maximum possible number of dimensions for a
variable is given by the predefined constant NC MAX VAR DIMS.
nattsp Pointer to location for returned number of variable attributes assigned to this
variable.
These functions return the value NC NOERR if no errors occurred. Otherwise, the
returned status indicates an error. Possible causes of errors include:
The variable ID is invalid for the specified netCDF dataset. The specified netCDF ID
does not refer to an open netCDF dataset.
Example
Here is an example using nc inq var to find out about a variable named rh in an existing
netCDF dataset named foo.nc:
#include <netcdf.h>
...
int status /* error status */
int ncid; /* netCDF ID */
int rh_id; /* variable ID */
nc_type rh_type; /* variable type */
42 NetCDF C Interface Guide
Usage
int nc_put_var1_text (int ncid, int varid, const size_t index[],
const char *tp);
int nc_put_var1_uchar (int ncid, int varid, const size_t index[],
const unsigned char *up);
int nc_put_var1_schar (int ncid, int varid, const size_t index[],
const signed char *cp);
int nc_put_var1_short (int ncid, int varid, const size_t index[],
const short *sp);
int nc_put_var1_int (int ncid, int varid, const size_t index[],
const int *ip);
int nc_put_var1_long (int ncid, int varid, const size_t index[],
const long *lp);
int nc_put_var1_float (int ncid, int varid, const size_t index[],
const float *fp);
int nc_put_var1_double(int ncid, int varid, const size_t index[],
const double *dp);
ncid NetCDF ID, from a previous call to nc open or nc create.
varid Variable ID.
index[] The index of the data value to be written. The indices are relative to 0, so for ex-
ample, the first data value of a two-dimensional variable would have index (0,0).
The elements of index must correspond to the variable’s dimensions. Hence, if
the variable uses the unlimited dimension, the first index would correspond to
the unlimited dimension.
Chapter 4: Variables 43
tp
up
cp
sp
ip
lp
fp
dp Pointer to the data value to be written. If the type of data values differs
from the netCDF variable type, type conversion will occur. See section “Type
Conversion” in The NetCDF Users Guide.
Errors
nc put var1 type returns the value NC NOERR if no errors occurred. Otherwise, the
returned status indicates an error. Possible causes of errors include:
• The variable ID is invalid for the specified netCDF dataset.
• The specified indices were out of range for the rank of the specified variable. For
example, a negative index or an index that is larger than the corresponding dimension
length will cause an error.
• The specified value is out of the range of values representable by the external data type
of the variable.
• The specified netCDF is in define mode rather than data mode.
• The specified netCDF ID does not refer to an open netCDF dataset.
Example
Here is an example using nc put var1 double to set the (1,2,3) element of the variable named
rh to 0.5 in an existing netCDF dataset named foo.nc. For simplicity in this example, we
assume that we know that rh is dimensioned with time, lat, and lon, so we want to set the
value of rh that corresponds to the second time value, the third lat value, and the fourth
lon value:
#include <netcdf.h>
...
int status; /* error status */
int ncid; /* netCDF ID */
int rh_id; /* variable ID */
static size_t rh_index[] = {1, 2, 3}; /* where to put value */
static double rh_val = 0.5; /* value to put */
...
status = nc_open("foo.nc", NC_WRITE, &ncid);
if (status != NC_NOERR) handle_error(status);
...
status = nc_inq_varid (ncid, "rh", &rh_id);
if (status != NC_NOERR) handle_error(status);
...
status = nc_put_var1_double(ncid, rh_id, rh_index, &rh_val);
if (status != NC_NOERR) handle_error(status);
44 NetCDF C Interface Guide
Usage
int nc_put_var_text (int ncid, int varid, const char *tp);
int nc_put_var_uchar (int ncid, int varid, const unsigned char *up);
int nc_put_var_schar (int ncid, int varid, const signed char *cp);
int nc_put_var_short (int ncid, int varid, const short *sp);
int nc_put_var_int (int ncid, int varid, const int *ip);
int nc_put_var_long (int ncid, int varid, const long *lp);
int nc_put_var_float (int ncid, int varid, const float *fp);
int nc_put_var_double(int ncid, int varid, const double *dp);
ncid NetCDF ID, from a previous call to nc open or nc create.
varid Variable ID.
tp
up
cp
sp
ip
lp
fp
dp Pointer to a block of data values to be written. The order in which the data will
be written to the netCDF variable is with the last dimension of the specified
variable varying fastest. If the type of data values differs from the netCDF
variable type, type conversion will occur. See section “Type Conversion” in
The NetCDF Users Guide.
Errors
Members of the nc put var type family return the value NC NOERR if no errors occurred.
Otherwise, the returned status indicates an error. Possible causes of errors include:
• The variable ID is invalid for the specified netCDF dataset.
• One or more of the specified values are out of the range of values representable by the
external data type of the variable.
Chapter 4: Variables 45
• One or more of the specified values are out of the range of values representable by the
external data type of the variable.
• The specified netCDF dataset is in define mode rather than data mode.
• The specified netCDF ID does not refer to an open netCDF dataset.
Example
Here is an example using nc put var double to add or change all the values of the variable
named rh to 0.5 in an existing netCDF dataset named foo.nc. For simplicity in this example,
we assume that we know that rh is dimensioned with time, lat, and lon, and that there are
three time values, five lat values, and ten lon values.
#include <netcdf.h>
...
#define TIMES 3
#define LATS 5
#define LONS 10
int status; /* error status */
int ncid; /* netCDF ID */
int rh_id; /* variable ID */
double rh_vals[TIMES*LATS*LONS]; /* array to hold values */
int i;
...
status = nc_open("foo.nc", NC_WRITE, &ncid);
if (status != NC_NOERR) handle_error(status);
...
status = nc_inq_varid (ncid, "rh", &rh_id);
if (status != NC_NOERR) handle_error(status);
...
for (i = 0; i < TIMES*LATS*LONS; i++)
rh_vals[i] = 0.5;
/* write values into netCDF variable */
status = nc_put_var_double(ncid, rh_id, rh_vals);
if (status != NC_NOERR) handle_error(status);
Usage
int nc_put_vara_ type (int ncid, int varid, const size_t start[],
const size_t count[], const type *valuesp);
int nc_put_vara_text (int ncid, int varid, const size_t start[],
46 NetCDF C Interface Guide
start A vector of size t integers specifying the index in the variable where the first
of the data values will be written. The indices are relative to 0, so for example,
the first data value of a variable would have index (0, 0, ... , 0). The size of
start must be the same as the number of dimensions of the specified variable.
The elements of start must correspond to the variable’s dimensions in order.
Hence, if the variable is a record variable, the first index would correspond to
the starting record number for writing the data values.
count A vector of size t integers specifying the edge lengths along each dimension of
the block of data values to be written. To write a single value, for example,
specify count as (1, 1, ... , 1). The length of count is the number of dimensions
of the specified variable. The elements of count correspond to the variable’s
dimensions. Hence, if the variable is a record variable, the first element of
count corresponds to a count of the number of records to write.
tp
up
cp
sp
ip
lp
fp
dp Pointer to a block of data values to be written. The order in which the data will
be written to the netCDF variable is with the last dimension of the specified
variable varying fastest. If the type of data values differs from the netCDF
variable type, type conversion will occur. See section “Type Conversion” in
The NetCDF Users Guide.
Chapter 4: Variables 47
Errors
nc put vara type returns the value NC NOERR if no errors occurred. Otherwise, the
returned status indicates an error. Possible causes of errors include:
• The variable ID is invalid for the specified netCDF dataset.
• The specified corner indices were out of range for the rank of the specified variable. For
example, a negative index, or an index that is larger than the corresponding dimension
length will cause an error.
• The specified edge lengths added to the specified corner would have referenced data
out of range for the rank of the specified variable. For example, an edge length that is
larger than the corresponding dimension length minus the corner index will cause an
error.
• One or more of the specified values are out of the range of values representable by the
external data type of the variable.
• The specified netCDF dataset is in define mode rather than data mode.
• The specified netCDF ID does not refer to an open netCDF dataset.
Example
Here is an example using nc put vara double to add or change all the values of the variable
named rh to 0.5 in an existing netCDF dataset named foo.nc. For simplicity in this example,
we assume that we know that rh is dimensioned with time, lat, and lon, and that there are
three time values, five lat values, and ten lon values.
#include <netcdf.h>
...
#define TIMES 3
#define LATS 5
#define LONS 10
int status; /* error status */
int ncid; /* netCDF ID */
int rh_id; /* variable ID */
static size_t start[] = {0, 0, 0}; /* start at first value */
static size_t count[] = {TIMES, LATS, LONS};
double rh_vals[TIMES*LATS*LONS]; /* array to hold values */
int i;
...
status = nc_open("foo.nc", NC_WRITE, &ncid);
if (status != NC_NOERR) handle_error(status);
...
status = nc_inq_varid (ncid, "rh", &rh_id);
if (status != NC_NOERR) handle_error(status);
...
for (i = 0; i < TIMES*LATS*LONS; i++)
rh_vals[i] = 0.5;
/* write values into netCDF variable */
status = nc_put_vara_double(ncid, rh_id, start, count, rh_vals);
if (status != NC_NOERR) handle_error(status);
48 NetCDF C Interface Guide
Usage
int nc_put_vars_text (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
const char *tp);
int nc_put_vars_uchar (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
const unsigned char *up);
int nc_put_vars_schar (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
const signed char *cp);
int nc_put_vars_short (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
const short *sp);
int nc_put_vars_int (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
const int *ip);
int nc_put_vars_long (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
const long *lp);
int nc_put_vars_float (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
const float *fp);
int nc_put_vars_double(int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
const double *dp);
ncid NetCDF ID, from a previous call to nc open or nc create.
varid Variable ID.
start A vector of size t integers specifying the index in the variable where the first
of the data values will be written. The indices are relative to 0, so for example,
the first data value of a variable would have index (0, 0, ... , 0). The elements of
start correspond, in order, to the variable’s dimensions. Hence, if the variable
is a record variable, the first index corresponds to the starting record number
for writing the data values.
count A vector of size t integers specifying the number of indices selected along each
dimension. To write a single value, for example, specify count as (1, 1, ... ,
1). The elements of count correspond, in order, to the variable’s dimensions.
Hence, if the variable is a record variable, the first element of count corresponds
to a count of the number of records to write.
Chapter 4: Variables 49
stride A vector of ptrdiff t integers that specifies the sampling interval along each di-
mension of the netCDF variable. The elements of the stride vector correspond,
in order, to the netCDF variable’s dimensions (stride[0] gives the sampling inter-
val along the most slowly varying dimension of the netCDF variable). Sampling
intervals are specified in type-independent units of elements (a value of 1 selects
consecutive elements of the netCDF variable along the corresponding dimen-
sion, a value of 2 selects every other element, etc.). A NULL stride argument
is treated as (1, 1, ... , 1).
tp
up
cp
sp
ip
lp
fp
dp Pointer to a block of data values to be written. The order in which the data will
be written to the netCDF variable is with the last dimension of the specified
variable varying fastest. If the type of data values differs from the netCDF
variable type, type conversion will occur. See section “Type Conversion” in
The NetCDF Users Guide.
Errors
nc put vars type returns the value NC NOERR if no errors occurred. Otherwise, the
returned status indicates an error. Possible causes of errors include:
• The variable ID is invalid for the specified netCDF dataset.
• The specified start, count and stride generate an index which is out of range.
• One or more of the specified values are out of the range of values representable by the
external data type of the variable.
• The specified netCDF is in define mode rather than data mode.
• The specified netCDF ID does not refer to an open netCDF dataset.
Example
Here is an example of using nc put vars float to write – from an internal array – every
other point of a netCDF variable named rh which is described by the C declaration float
rh[4][6] (note the size of the dimensions):
#include <netcdf.h>
...
#define NDIM 2 /* rank of netCDF variable */
int ncid; /* netCDF ID */
int status; /* error status */
int rhid; /* variable ID */
static size_t start[NDIM] /* netCDF variable start point: */
= {0, 0}; /* first element */
static size_t count[NDIM] /* size of internal array: entire */
50 NetCDF C Interface Guide
Usage
int nc_put_varm_text (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
const ptrdiff_t imap[], const char *tp);
int nc_put_varm_uchar (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
const ptrdiff_t imap[], const unsigned char *up);
int nc_put_varm_schar (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
const ptrdiff_t imap[], const signed char *cp);
int nc_put_varm_short (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
const ptrdiff_t imap[], const short *sp);
int nc_put_varm_int (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
const ptrdiff_t imap[], const int *ip);
int nc_put_varm_long (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
const ptrdiff_t imap[], const long *lp);
int nc_put_varm_float (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
const ptrdiff_t imap[], const float *fp);
Chapter 4: Variables 51
data values differs from the netCDF variable type, type conversion will occur.
See section “Type Conversion” in The NetCDF Users Guide.
Errors
nc put varm type returns the value NC NOERR if no errors occurred. Otherwise, the
returned status indicates an error. Possible causes of errors include:
• The variable ID is invalid for the specified netCDF dataset.
• The specified start, count, and stride generate an index which is out of range. Note
that no error checking is possible on the imap vector.
• One or more of the specified values are out of the range of values representable by the
external data type of the variable.
• The specified netCDF is in define mode rather than data mode.
• The specified netCDF ID does not refer to an open netCDF dataset.
Example
The following imap vector maps in the trivial way a 4x3x2 netCDF variable and an internal
array of the same shape:
float a[4][3][2]; /* same shape as netCDF variable */
int imap[3] = {6, 2, 1};
/* netCDF dimension inter-element distance */
/* ---------------- ---------------------- */
/* most rapidly varying 1 */
/* intermediate 2 (=imap[2]*2) */
/* most slowly varying 6 (=imap[1]*3) */
Using the imap vector above with nc put varm float obtains the same result as simply
using nc put var float.
Here is an example of using nc put varm float to write – from a transposed, internal
array – a netCDF variable named rh which is described by the C declaration float rh[6][4]
(note the size and order of the dimensions):
#include <netcdf.h>
...
#define NDIM 2 /* rank of netCDF variable */
int ncid; /* netCDF ID */
int status; /* error status */
int rhid; /* variable ID */
static size_t start[NDIM] /* netCDF variable start point: */
= {0, 0}; /* first element */
static size_t count[NDIM] /* size of internal array: entire netCDF */
= {6, 4}; /* variable; order corresponds to netCDF */
/* variable -- not internal array */
static ptrdiff_t stride[NDIM]/* variable subsampling intervals: */
= {1, 1}; /* sample every netCDF element */
static ptrdiff_t imap[NDIM] /* internal array inter-element distances; */
= {1, 6}; /* would be {4, 1} if not transposing */
Chapter 4: Variables 53
value will be read. The value is converted from the external data type of the variable, if
necessary.
Usage
int nc_get_var1_text (int ncid, int varid, const size_t index[],
char *tp);
int nc_get_var1_uchar (int ncid, int varid, const size_t index[],
unsigned char *up);
int nc_get_var1_schar (int ncid, int varid, const size_t index[],
signed char *cp);
int nc_get_var1_short (int ncid, int varid, const size_t index[],
short *sp);
int nc_get_var1_int (int ncid, int varid, const size_t index[],
int *ip);
int nc_get_var1_long (int ncid, int varid, const size_t index[],
long *lp);
int nc_get_var1_float (int ncid, int varid, const size_t index[],
float *fp);
int nc_get_var1_double(int ncid, int varid, const size_t index[],
double *dp);
ncid NetCDF ID, from a previous call to nc open or nc create.
varid Variable ID.
index[] The index of the data value to be read. The indices are relative to 0, so for
example, the first data value of a two-dimensional variable would have index
(0,0). The elements of index must correspond to the variable’s dimensions.
Hence, if the variable is a record variable, the first index is the record number.
tp
up
cp
sp
ip
lp
fp
dp Pointer to the location into which the data value is read. If the type of data
value differs from the netCDF variable type, type conversion will occur. See
section “Type Conversion” in The NetCDF Users Guide.
Errors
nc get var1 type returns the value NC NOERR if no errors occurred. Otherwise, the
returned status indicates an error. Possible causes of errors include:
• The variable ID is invalid for the specified netCDF dataset.
• The specified indices were out of range for the rank of the specified variable. For
example, a negative index or an index that is larger than the corresponding dimension
length will cause an error.
Chapter 4: Variables 55
• The value is out of the range of values representable by the desired data type.
• The specified netCDF is in define mode rather than data mode.
• The specified netCDF ID does not refer to an open netCDF dataset.
Example
Here is an example using nc get var1 double to get the (1,2,3) element of the variable
named rh in an existing netCDF dataset named foo.nc. For simplicity in this example, we
assume that we know that rh is dimensioned with time, lat, and lon, so we want to get the
value of rh that corresponds to the second time value, the third lat value, and the fourth
lon value:
#include <netcdf.h>
...
int status; /* error status */
int ncid; /* netCDF ID */
int rh_id; /* variable ID */
static size_t rh_index[] = {1, 2, 3}; /* where to get value from */
double rh_val; /* where to put it */
...
status = nc_open("foo.nc", NC_NOWRITE, &ncid);
if (status != NC_NOERR) handle_error(status);
...
status = nc_inq_varid (ncid, "rh", &rh_id);
if (status != NC_NOERR) handle_error(status);
...
status = nc_get_var1_double(ncid, rh_id, rh_index, &rh_val);
if (status != NC_NOERR) handle_error(status);
Usage
int nc_get_var_text (int ncid, int varid, char *tp);
int nc_get_var_uchar (int ncid, int varid, unsigned char *up);
int nc_get_var_schar (int ncid, int varid, signed char *cp);
int nc_get_var_short (int ncid, int varid, short *sp);
int nc_get_var_int (int ncid, int varid, int *ip);
56 NetCDF C Interface Guide
Errors
nc get var type returns the value NC NOERR if no errors occurred. Otherwise, the re-
turned status indicates an error. Possible causes of errors include:
• The variable ID is invalid for the specified netCDF dataset.
• One or more of the values are out of the range of values representable by the desired
type.
• The specified netCDF is in define mode rather than data mode.
• The specified netCDF ID does not refer to an open netCDF dataset.
Example
Here is an example using nc get var double to read all the values of the variable named rh
from an existing netCDF dataset named foo.nc. For simplicity in this example, we assume
that we know that rh is dimensioned with time, lat, and lon, and that there are three time
values, five lat values, and ten lon values.
#include <netcdf.h>
...
#define TIMES 3
#define LATS 5
#define LONS 10
int status; /* error status */
int ncid; /* netCDF ID */
int rh_id; /* variable ID */
double rh_vals[TIMES*LATS*LONS]; /* array to hold values */
...
status = nc_open("foo.nc", NC_NOWRITE, &ncid);
if (status != NC_NOERR) handle_error(status);
...
Chapter 4: Variables 57
Usage
int nc_get_vara_text (int ncid, int varid, const size_t start[],
const size_t count[] char *tp);
int nc_get_vara_uchar (int ncid, int varid, const size_t start[],
const size_t count[] unsigned char *up);
int nc_get_vara_schar (int ncid, int varid, const size_t start[],
const size_t count[] signed char *cp);
int nc_get_vara_short (int ncid, int varid, const size_t start[],
const size_t count[] short *sp);
int nc_get_vara_int (int ncid, int varid, const size_t start[],
const size_t count[] int *ip);
int nc_get_vara_long (int ncid, int varid, const size_t start[],
const size_t count[] long *lp);
int nc_get_vara_float (int ncid, int varid, const size_t start[],
const size_t count[] float *fp);
int nc_get_vara_double(int ncid, int varid, const size_t start[],
const size_t count[] double *dp);
dimensions. Hence, if the variable is a record variable, the first element of count
corresponds to a count of the number of records to read.
tp
up
cp
sp
ip
lp
fp
dp Pointer to the location into which the data value is read. If the type of data
value differs from the netCDF variable type, type conversion will occur. See
section “Type Conversion” in The NetCDF Users Guide.
Errors
nc get vara type returns the value NC NOERR if no errors occurred. Otherwise, the
returned status indicates an error. Possible causes of errors include:
• The variable ID is invalid for the specified netCDF dataset.
• The specified corner indices were out of range for the rank of the specified variable. For
example, a negative index or an index that is larger than the corresponding dimension
length will cause an error.
• The specified edge lengths added to the specified corner would have referenced data
out of range for the rank of the specified variable. For example, an edge length that is
larger than the corresponding dimension length minus the corner index will cause an
error.
• One or more of the values are out of the range of values representable by the desired
type.
• The specified netCDF is in define mode rather than data mode.
• The specified netCDF ID does not refer to an open netCDF dataset.
Example
Here is an example using nc get vara double to read all the values of the variable named rh
from an existing netCDF dataset named foo.nc. For simplicity in this example, we assume
that we know that rh is dimensioned with time, lat, and lon, and that there are three time
values, five lat values, and ten lon values.
#include <netcdf.h>
...
#define TIMES 3
#define LATS 5
#define LONS 10
int status; /* error status */
int ncid; /* netCDF ID */
int rh_id; /* variable ID */
static size_t start[] = {0, 0, 0}; /* start at first value */
static size_t count[] = {TIMES, LATS, LONS};
Chapter 4: Variables 59
Usage
int nc_get_vars_text (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
char *tp);
int nc_get_vars_uchar (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
unsigned char *up);
int nc_get_vars_schar (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
signed char *cp);
int nc_get_vars_short (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
short *sp);
int nc_get_vars_int (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
int *ip);
int nc_get_vars_long (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
long *lp);
int nc_get_vars_float (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
float *fp);
int nc_get_vars_double(int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
double *dp)
ncid NetCDF ID, from a previous call to nc open or nc create.
60 NetCDF C Interface Guide
Errors
nc get vars type returns the value NC NOERR if no errors occurred. Otherwise, the
returned status indicates an error. Possible causes of errors include:
• The variable ID is invalid for the specified netCDF dataset.
• The specified start, count and stride generate an index which is out of range.
• One or more of the values are out of the range of values representable by the desired
type.
• The specified netCDF is in define mode rather than data mode.
• The specified netCDF ID does not refer to an open netCDF dataset.
Example
Here is an example that uses nc get vars double to read every other value in each dimension
of the variable named rh from an existing netCDF dataset named foo.nc. For simplicity in
this example, we assume that we know that rh is dimensioned with time, lat, and lon, and
that there are three time values, five lat values, and ten lon values.
Chapter 4: Variables 61
#include <netcdf.h>
...
#define TIMES 3
#define LATS 5
#define LONS 10
int status; /* error status */
int ncid; /* netCDF ID */
int rh_id; /* variable ID */
static size_t start[] = {0, 0, 0}; /* start at first value */
static size_t count[] = {TIMES, LATS, LONS};
static ptrdiff_t stride[] = {2, 2, 2};/* every other value */
double data[TIMES][LATS][LONS]; /* array to hold values */
...
status = nc_open("foo.nc", NC_NOWRITE, &ncid);
if (status != NC_NOERR) handle_error(status);
...
status = nc_inq_varid (ncid, "rh", &rh_id);
if (status != NC_NOERR) handle_error(status);
...
/* read subsampled values from netCDF variable into array */
status = nc_get_vars_double(ncid, rh_id, start, count, stride,
&data[0][0][0]);
if (status != NC_NOERR) handle_error(status);
...
Usage
int nc_get_varm_text (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
const ptrdiff_t imap[], char *tp);
int nc_get_varm_uchar (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
const ptrdiff_t imap[], unsigned char *up);
int nc_get_varm_schar (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
const ptrdiff_t imap[], signed char *cp);
int nc_get_varm_short (int ncid, int varid, const size_t start[],
const size_t count[], const ptrdiff_t stride[],
62 NetCDF C Interface Guide
tp
up
cp
sp
ip
lp
fp
dp Pointer to the location used for computing where the data values are read; the
data should be of the type appropriate for the function called. If the type of
data value differs from the netCDF variable type, type conversion will occur.
See section “Type Conversion” in The NetCDF Users Guide.
Errors
nc get varm type returns the value NC NOERR if no errors occurred. Otherwise, the
returned status indicates an error. Possible causes of errors include:
• The variable ID is invalid for the specified netCDF dataset.
• The specified start, count, and stride generate an index which is out of range. Note
that no error checking is possible on the imap vector.
• One or more of the values are out of the range of values representable by the desired
type.
• The specified netCDF is in define mode rather than data mode.
• The specified netCDF ID does not refer to an open netCDF dataset.
Example
The following imap vector maps in the trivial way a 4x3x2 netCDF variable and an internal
array of the same shape:
float a[4][3][2]; /* same shape as netCDF variable */
size_t imap[3] = {6, 2, 1};
/* netCDF dimension inter-element distance */
/* ---------------- ---------------------- */
/* most rapidly varying 1 */
/* intermediate 2 (=imap[2]*2) */
/* most slowly varying 6 (=imap[1]*3) */
Using the imap vector above with nc get varm float obtains the same result as simply
using nc get var float.
Here is an example of using nc get varm float to transpose a netCDF variable named
rh which is described by the C declaration float rh[6][4] (note the size and order of the
dimensions):
#include <netcdf.h>
...
#define NDIM 2 /* rank of netCDF variable */
int ncid; /* netCDF ID */
int status; /* error status */
int rhid; /* variable ID */
64 NetCDF C Interface Guide
...
status = nc_get_varm_float(ncid, rhid, start, count, stride, imap, rh);
if (status != NC_NOERR) handle_error(status);
size_t tx_start[TDIMS];
size_t tx_count[TDIMS];
static char tx_val[] =
"example string"; /* string to be put */
...
status = nc_open("foo.nc", NC_WRITE, &ncid);
if (status != NC_NOERR) handle_error(status);
status = nc_redef(ncid); /* enter define mode */
if (status != NC_NOERR) handle_error(status);
...
/* define character-position dimension for strings of max length 40 */
status = nc_def_dim(ncid, "chid", 40L, &chid);
if (status != NC_NOERR) handle_error(status);
...
/* define a character-string variable */
tx_dims[0] = timeid;
tx_dims[1] = chid; /* character-position dimension last */
status = nc_def_var (ncid, "tx", NC_CHAR, TDIMS, tx_dims, &tx_id);
if (status != NC_NOERR) handle_error(status);
...
status = nc_enddef(ncid); /* leave define mode */
if (status != NC_NOERR) handle_error(status);
...
/* write tx_val into tx netCDF variable in record 3 */
tx_start[0] = 3; /* record number to write */
tx_start[1] = 0; /* start at beginning of variable */
tx_count[0] = 1; /* only write one record */
tx_count[1] = strlen(tx_val) + 1; /* number of chars to write */
status = nc_put_vara_text(ncid, tx_id, tx_start, tx_count, tx_val);
if (status != NC_NOERR) handle_error(status);
You may ignore fill values and use the entire range of a netCDF external data type, but
in this case you should make sure you write all data values before reading them. If you
know you will be writing all the data before reading it, you can specify that no prefilling of
variables with fill values will occur by calling nc set fill before writing. This may provide a
significant performance gain for netCDF writes.
Chapter 4: Variables 67
The variable attribute FillValue may be used to specify the fill value for a
variable. Their are default fill values for each type, defined in the include file
netcdf.h: NC FILL CHAR, NC FILL BYTE, NC FILL SHORT, NC FILL INT,
NC FILL FLOAT, and NC FILL DOUBLE.
The netCDF byte and character types have different default fill values. The default fill
value for characters is the zero byte, a useful value for detecting the end of variable-length
C character strings. If you need a fill value for a byte variable, it is recommended that you
explicitly define an appropriate FillValue attribute, as generic utilities such as ncdump will
not assume a default fill value for byte variables.
Type conversion for fill values is identical to type conversion for other values: attempting
to convert a value from one type to another type that can’t represent the value results in
a range error. Such errors may occur on writing or reading values from a larger type (such
as double) to a smaller type (such as float), if the fill value for the larger type cannot be
represented in the smaller type.
Usage
int nc rename var(int ncid, int varid, const char* name);
ncid NetCDF ID, from a previous call to nc open or nc create.
varid Variable ID.
name New name for the specified variable.
Errors
nc rename var returns the value NC NOERR if no errors occurred. Otherwise, the returned
status indicates an error. Possible causes of errors include:
The new name is in use as the name of another variable. The variable ID is invalid for
the specified netCDF dataset. The specified netCDF ID does not refer to an open netCDF
dataset.
Example
Here is an example using nc rename var to rename the variable rh to rel hum in an existing
netCDF dataset named foo.nc:
#include <netcdf.h>
...
int status; /* error status */
int ncid; /* netCDF ID */
int rh_id; /* variable ID */
...
status = nc_open("foo.nc", NC_WRITE, &ncid);
68 NetCDF C Interface Guide
5 Attributes
5.1 Introduction
Attributes may be associated with each netCDF variable to specify such properties as units,
special values, maximum and minimum valid values, scaling factors, and offsets. Attributes
for a netCDF dataset are defined when the dataset is first created, while the netCDF dataset
is in define mode. Additional attributes may be added later by reentering define mode. A
netCDF attribute has a netCDF variable to which it is assigned, a name, a type, a length,
and a sequence of one or more values. An attribute is designated by its variable ID and
name. When an attribute name is not known, it may be designated by its variable ID and
number in order to determine its name, using the function nc inq attname.
The attributes associated with a variable are typically defined immediately after the
variable is created, while still in define mode. The data type, length, and value of an
attribute may be changed even when in data mode, as long as the changed attribute requires
no more space than the attribute as originally defined.
It is also possible to have attributes that are not associated with any variable. These are
called global attributes and are identified by using NC GLOBAL as a variable pseudo-ID.
Global attributes are usually related to the netCDF dataset as a whole and may be used
for purposes such as providing a title or processing history for a netCDF dataset.
Operations supported on attributes are:
• Create an attribute, given its variable ID, name, data type, length, and value.
• Get attribute’s data type and length from its variable ID and name.
• Get attribute’s value from its variable ID and name.
• Copy attribute from one netCDF variable to another.
• Get name of attribute from its number.
• Rename an attribute.
• Delete an attribute.
Usage
Although it’s possible to create attributes of all types, text and double attributes are ade-
quate for most purposes.
int nc_put_att_text (int ncid, int varid, const char *name,
size_t len, const char *tp);
int nc_put_att_uchar (int ncid, int varid, const char *name,
nc_type xtype, size_t len, const unsigned char *up);
int nc_put_att_schar (int ncid, int varid, const char *name,
nc_type xtype, size_t len, const signed char *cp);
70 NetCDF C Interface Guide
Errors
nc put att type returns the value NC NOERR if no errors occurred. Otherwise, the
returned status indicates an error. Possible causes of errors include:
• The variable ID is invalid for the specified netCDF dataset.
• The specified netCDF type is invalid.
• The specified length is negative.
• The specified open netCDF dataset is in data mode and the specified attribute would
expand.
• The specified open netCDF dataset is in data mode and the specified attribute does
not already exist.
• The specified netCDF ID does not refer to an open netCDF dataset.
• The number of attributes for this variable exceeds NC MAX ATTRS.
Chapter 5: Attributes 71
Example
Here is an example using nc put att double to add a variable attribute named valid range
for a netCDF variable named rh and a global attribute named title to an existing netCDF
dataset named foo.nc:
#include <netcdf.h>
...
int status; /* error status */
int ncid; /* netCDF ID */
int rh_id; /* variable ID */
static double rh_range[] = {0.0, 100.0};/* attribute vals */
static char title[] = "example netCDF dataset";
...
status = nc_open("foo.nc", NC_WRITE, &ncid);
if (status != NC_NOERR) handle_error(status);
...
status = nc_redef(ncid); /* enter define mode */
if (status != NC_NOERR) handle_error(status);
status = nc_inq_varid (ncid, "rh", &rh_id);
if (status != NC_NOERR) handle_error(status);
...
status = nc_put_att_double (ncid, rh_id, "valid_range",
NC_DOUBLE, 2, rh_range);
if (status != NC_NOERR) handle_error(status);
status = nc_put_att_text (ncid, NC_GLOBAL, "title",
strlen(title), title)
if (status != NC_NOERR) handle_error(status);
...
status = nc_enddef(ncid); /* leave define mode */
if (status != NC_NOERR) handle_error(status);
The function nc inq attname gets the name of an attribute, given its variable ID and
number. This function is useful in generic applications that need to get the names of all
the attributes associated with a variable, since attributes are accessed by name rather than
number in all other attribute functions. The number of an attribute is more volatile than
the name, since it can change when other attributes of the same variable are deleted. This
is why an attribute number is not called an attribute ID.
The function nc inq att returns the attribute’s type and length. The other functions
each return just one item of information about an attribute.
72 NetCDF C Interface Guide
Usage
int nc_inq_att (int ncid, int varid, const char *name,
nc_type *xtypep, size_t *lenp);
int nc_inq_atttype(int ncid, int varid, const char *name,
nc_type *xtypep);
int nc_inq_attlen (int ncid, int varid, const char *name, size_t *lenp);
int nc_inq_attname(int ncid, int varid, int attnum, char *name);
int nc_inq_attid (int ncid, int varid, const char *name, int *attnump);
ncid NetCDF ID, from a previous call to nc open or nc create.
varid Variable ID of the attribute’s variable, or NC GLOBAL for a global attribute.
name Attribute name. For nc inq attname, this is a pointer to the location for the
returned attribute name.
xtypep Pointer to location for returned attribute type, one of the set of predefined
netCDF external data types. The type of this parameter, nc type, is defined in
the netCDF header file. The valid netCDF external data types are NC BYTE,
NC CHAR, NC SHORT, NC INT, NC FLOAT, and NC DOUBLE. If this
parameter is given as ’0’ (a null pointer), no type will be returned so no variable
to hold the type needs to be declared.
lenp Pointer to location for returned number of values currently stored in the at-
tribute. For attributes of type NC CHAR, you should not assume that this
includes a trailing zero byte; it doesn’t if the attribute was stored without a
trailing zero byte, for example from a FORTRAN program. Before using the
value as a C string, make sure it is null-terminated. If this parameter is given
as ’0’ (a null pointer), no length will be returned so no variable to hold this
information needs to be declared.
attnum For nc inq attname, attribute number. The attributes for each variable are
numbered from 0 (the first attribute) to natts-1, where natts is the number of
attributes for the variable, as returned from a call to nc inq varnatts.
attnump For nc inq attid, pointer to location for returned attribute number that specifies
which attribute this is for this variable (or which global attribute). If you
already know the attribute name, knowing its number is not very useful, because
accessing information about an attribute requires its name.
Errors
Each function returns the value NC NOERR if no errors occurred. Otherwise, the returned
status indicates an error. Possible causes of errors include:
• The variable ID is invalid for the specified netCDF dataset.
• The specified attribute does not exist.
• The specified netCDF ID does not refer to an open netCDF dataset.
• For nc inq attname, the specified attribute number is negative or more than the number
of attributes defined for the specified variable.
Chapter 5: Attributes 73
Example
Here is an example using nc inq att to find out the type and length of a variable attribute
named valid range for a netCDF variable named rh and a global attribute named title in
an existing netCDF dataset named foo.nc:
#include <netcdf.h>
...
int status; /* error status */
int ncid; /* netCDF ID */
int rh_id; /* variable ID */
nc_type vr_type, t_type; /* attribute types */
int vr_len, t_len; /* attribute lengths */
...
status = nc_open("foo.nc", NC_NOWRITE, &ncid);
if (status != NC_NOERR) handle_error(status);
...
status = nc_inq_varid (ncid, "rh", &rh_id);
if (status != NC_NOERR) handle_error(status);
...
status = nc_inq_att (ncid, rh_id, "valid_range", &vr_type, &vr_len);
if (status != NC_NOERR) handle_error(status);
status = nc_inq_att (ncid, NC_GLOBAL, "title", &t_type, &t_len);
if (status != NC_NOERR) handle_error(status);
Usage
int nc_get_att_text (int ncid, int varid, const char *name,
char *tp);
int nc_get_att_uchar (int ncid, int varid, const char *name,
unsigned char *up);
int nc_get_att_schar (int ncid, int varid, const char *name,
signed char *cp);
int nc_get_att_short (int ncid, int varid, const char *name,
short *sp);
int nc_get_att_int (int ncid, int varid, const char *name,
int *ip);
int nc_get_att_long (int ncid, int varid, const char *name,
long *lp);
int nc_get_att_float (int ncid, int varid, const char *name,
float *fp);
int nc_get_att_double (int ncid, int varid, const char *name,
double *dp);
74 NetCDF C Interface Guide
Errors
nc get att type returns the value NC NOERR if no errors occurred. Otherwise, the re-
turned status indicates an error. Possible causes of errors include:
• The variable ID is invalid for the specified netCDF dataset.
• The specified attribute does not exist.
• The specified netCDF ID does not refer to an open netCDF dataset.
• One or more of the attribute values are out of the range of values representable by the
desired type.
Example
Here is an example using nc get att double to determine the values of a variable attribute
named valid range for a netCDF variable named rh and a global attribute named title in
an existing netCDF dataset named foo.nc. In this example, it is assumed that we don’t
know how many values will be returned, but that we do know the types of the attributes.
Hence, to allocate enough space to store them, we must first inquire about the length of
the attributes.
#include <netcdf.h>
...
int status; /* error status */
int ncid; /* netCDF ID */
int rh_id; /* variable ID */
int vr_len, t_len; /* attribute lengths */
double *vr_val; /* ptr to attribute values */
char *title; /* ptr to attribute values */
extern char *malloc(); /* memory allocator */
Chapter 5: Attributes 75
...
status = nc_open("foo.nc", NC_NOWRITE, &ncid);
if (status != NC_NOERR) handle_error(status);
...
status = nc_inq_varid (ncid, "rh", &rh_id);
if (status != NC_NOERR) handle_error(status);
...
/* find out how much space is needed for attribute values */
status = nc_inq_attlen (ncid, rh_id, "valid_range", &vr_len);
if (status != NC_NOERR) handle_error(status);
status = nc_inq_attlen (ncid, NC_GLOBAL, "title", &t_len);
if (status != NC_NOERR) handle_error(status);
Usage
int nc_copy_att (int ncid_in, int varid_in, const char *name,
int ncid_out, int varid_out);
ncid_in The netCDF ID of an input netCDF dataset from which the attribute will be
copied, from a previous call to nc open or nc create.
varid_in ID of the variable in the input netCDF dataset from which the attribute will
be copied, or NC GLOBAL for a global attribute.
name Name of the attribute in the input netCDF dataset to be copied.
ncid_out The netCDF ID of the output netCDF dataset to which the attribute will be
copied, from a previous call to nc open or nc create. It is permissible for the
input and output netCDF IDs to be the same. The output netCDF dataset
should be in define mode if the attribute to be copied does not already exist for
the target variable, or if it would cause an existing target attribute to grow.
76 NetCDF C Interface Guide
varid_out
ID of the variable in the output netCDF dataset to which the attribute will be
copied, or NC GLOBAL to copy to a global attribute.
Errors
nc copy att returns the value NC NOERR if no errors occurred. Otherwise, the returned
status indicates an error. Possible causes of errors include:
• The input or output variable ID is invalid for the specified netCDF dataset.
• The specified attribute does not exist.
• The output netCDF is not in define mode and the attribute is new for the output
dataset is larger than the existing attribute.
• The input or output netCDF ID does not refer to an open netCDF dataset.
Example
Here is an example using nc copy att to copy the variable attribute units from the variable
rh in an existing netCDF dataset named foo.nc to the variable avgrh in another existing
netCDF dataset named bar.nc, assuming that the variable avgrh already exists, but does
not yet have a units attribute:
#include <netcdf.h>
...
int status; /* error status */
int ncid1, ncid2; /* netCDF IDs */
int rh_id, avgrh_id; /* variable IDs */
...
status = nc_open("foo.nc", NC_NOWRITE, ncid1);
if (status != NC_NOERR) handle_error(status);
status = nc_open("bar.nc", NC_WRITE, ncid2);
if (status != NC_NOERR) handle_error(status);
...
status = nc_inq_varid (ncid1, "rh", &rh_id);
if (status != NC_NOERR) handle_error(status);
status = nc_inq_varid (ncid2, "avgrh", &avgrh_id);
if (status != NC_NOERR) handle_error(status);
...
status = nc_redef(ncid2); /* enter define mode */
if (status != NC_NOERR) handle_error(status);
/* copy variable attribute from "rh" to "avgrh" */
status = nc_copy_att(ncid1, rh_id, "units", ncid2, avgrh_id);
if (status != NC_NOERR) handle_error(status);
...
status = nc_enddef(ncid2); /* leave define mode */
if (status != NC_NOERR) handle_error(status);
Chapter 5: Attributes 77
Usage
int nc_rename_att (int ncid, int varid, const char* name,
const char* newname);
ncid NetCDF ID, from a previous call to nc open or nc create
varid ID of the attribute’s variable, or NC GLOBAL for a global attribute
name The current attribute name.
newname The new name to be assigned to the specified attribute. If the new name is
longer than the current name, the netCDF dataset must be in define mode.
Errors
nc rename att returns the value NC NOERR if no errors occurred. Otherwise, the returned
status indicates an error. Possible causes of errors include:
• The specified variable ID is not valid.
• The new attribute name is already in use for another attribute of the specified variable.
• The specified netCDF dataset is in data mode and the new name is longer than the
old name.
• The specified attribute does not exist.
• The specified netCDF ID does not refer to an open netCDF dataset.
Example
Here is an example using nc rename att to rename the variable attribute units to Units for
a variable rh in an existing netCDF dataset named foo.nc:
#include <netcdf.h>
...
int status; /* error status */
int ncid; /* netCDF ID */
int rh_id; /* variable id */
...
status = nc_open("foo.nc", NC_NOWRITE, &ncid);
if (status != NC_NOERR) handle_error(status);
...
status = nc_inq_varid (ncid, "rh", &rh_id);
if (status != NC_NOERR) handle_error(status);
...
/* rename attribute */
status = nc_rename_att(ncid, rh_id, "units", "Units");
if (status != NC_NOERR) handle_error(status);
78 NetCDF C Interface Guide
Usage
int nc del att (int ncid, int varid, const char* name);
ncid NetCDF ID, from a previous call to nc open or nc create.
varid ID of the attribute’s variable, or NC GLOBAL for a global attribute.
name The name of the attribute to be deleted.
Errors
nc del att returns the value NC NOERR if no errors occurred. Otherwise, the returned
status indicates an error. Possible causes of errors include:
• The specified variable ID is not valid.
• The specified netCDF dataset is in data mode.
• The specified attribute does not exist.
• The specified netCDF ID does not refer to an open netCDF dataset.
Example
Here is an example using nc del att to delete the variable attribute Units for a variable rh
in an existing netCDF dataset named foo.nc:
#include <netcdf.h>
...
int status; /* error status */
int ncid; /* netCDF ID */
int rh_id; /* variable ID */
...
status = nc_open("foo.nc", NC_WRITE, &ncid);
if (status != NC_NOERR) handle_error(status);
...
status = nc_inq_varid (ncid, "rh", &rh_id);
if (status != NC_NOERR) handle_error(status);
...
/* delete attribute */
status = nc_redef(ncid); /* enter define mode */
if (status != NC_NOERR) handle_error(status);
status = nc_del_att(ncid, rh_id, "Units");
if (status != NC_NOERR) handle_error(status);
status = nc_enddef(ncid); /* leave define mode */
if (status != NC_NOERR) handle_error(status);
Appendix A: Summary of C Interface 79
...
}
switch(xtype) {
/* deal with the data, according to type */
...
case NC_FLOAT:
fanalyze((float *)bufferp);
break;
case NC_DOUBLE:
danalyze((double *)bufferp);
break;
}
Here’s how you might handle this with the new netCDF-3 C interface:
/*
* I want to use doubles for my analysis.
*/
double dbuf[NDOUBLES];
int status;
This part of the function name indicates the type of the data container you are using in
your program: character string, unsigned char, signed char, and so on.
Also, all macro names in the public C interface begin with the prefix NC . For example,
the macro which was formerly MAX NC NAME is now NC MAX NAME, and the former
FILL FLOAT is now NC FILL FLOAT.
As previously mentioned, all the old names are still supported for backward compatibil-
ity.
ncattrename
nc rename att
ncclose nc close
nccreate nc create
ncdimdef nc def dim
ncdimid nc inq dimid
ncdiminq nc inq dim, nc inq dimlen, nc inq dimname
ncdimrename
nc rename dim
ncendef nc enddef
ncinquire
nc inq, nc inq natts, nc inq ndims, nc inq nvars, nc inq unlimdim
ncopen nc open
ncrecget (none)
ncrecinq (none)
ncrecput (none)
ncredef nc redef
ncsetfill
nc set fill
ncsync nc sync
nctypelen
(none)
ncvardef nc def var
ncvarget nc get vara double, nc get vara float, nc get vara int, nc get vara long,
nc get vara schar, nc get vara short, nc get vara text, nc get vara uchar
ncvarget1
nc get var1 double, nc get var1 float, nc get var1 int, nc get var1 long,
nc get var1 schar, nc get var1 short, nc get var1 text, nc get var1 uchar
ncvargetg
nc get varm double, nc get varm float, nc get varm int, nc get varm long,
nc get varm schar, nc get varm short, nc get varm text, nc get varm uchar,
nc get vars double, nc get vars float, nc get vars int, nc get vars long,
nc get vars schar, nc get vars short, nc get vars text, nc get vars uchar
ncvarid nc inq varid
ncvarinq nc inq var, nc inq vardimid, nc inq varname, nc inq varnatts,
nc inq varndims, nc inq vartype
Appendix B: NetCDF 2 C Transition Guide 91
ncvarput nc put vara double, nc put vara float, nc put vara int, nc put vara long,
nc put vara schar, nc put vara short, nc put vara text, nc put vara uchar
ncvarput1
nc put var1 double, nc put var1 float, nc put var1 int, nc put var1 long,
nc put var1 schar, nc put var1 short, nc put var1 text, nc put var1 uchar
ncvarputg
nc put varm double, nc put varm float, nc put varm int, nc put varm long,
nc put varm schar, nc put varm short, nc put varm text, nc put varm uchar,
nc put vars double, nc put vars float, nc put vars int, nc put vars long,
nc put vars schar, nc put vars short, nc put vars text, nc put vars uchar
ncvarrename
nc rename var
(none) nc inq libvers
(none) nc strerror
92 NetCDF C Interface Guide
Appendix C: Error Codes 93
Index
M
B mapped array section, writing . . . . . . . . . . . . . . . . 61
backing out of definitions . . . . . . . . . . . . . . . . . . . . . 25 mapped array, writing . . . . . . . . . . . . . . . . . . . . . . . . 50
backward compatibility with v2 API . . . . . . . . . . 85
bit lengths of data types . . . . . . . . . . . . . . . . . . . . . 37
byte vs. char fill values . . . . . . . . . . . . . . . . . . . . . . . 66 N
byte, zero . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
nc create . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
nc create, example . . . . . . . . . . . . . . . . . . . . . . . . . . 14
C nc create, flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
C API summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 nc enddef . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
call sequence, typical . . . . . . . . . . . . . . . . . . . . . . . . . . 3 nc enddef, example . . . . . . . . . . . . . . . . . . . . . . . . . 20
canceling definitions . . . . . . . . . . . . . . . . . . . . . . . . . 25 nc open . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
character-string data, writing . . . . . . . . . . . . . . . . . 65 nc open, example . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
code templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 NC 64BIT OFFSET . . . . . . . . . . . . . . . . . . . . . 11, 14
compiling with netCDF library . . . . . . . . . . . . . . . . 7 nc abort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
copying attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 nc abort, example . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
96 NetCDF C Interface Guide