Introduction to HDF5 
HDF5 User Guide 
HDF5 Reference Manual 
Other HDF5 documents and links 

Introduction to HDF5 Release 1.2

This is an introduction to the HDF5 data model and programming model. Being a Getting Started or QuickStart document, this Introduction to HDF5 is intended to provide enough information for you to develop a basic understanding of how HDF5 works and is meant to be used. Knowledge of the current version of HDF will make it easier to follow the text, but it is not required. More complete information of the sort you will need to actually use HDF5 is available in the HDF5 documentation. Available documents include the following:

Code examples are available in the source code tree when you install HDF5.


Table of Contents
Introduction to HDF5 Release 1.2

1. What Is HDF5?
    Why HDF5?
    Limitations of the Current Release
    Changes in the Current Release

2. HDF5 File Organization and
    Data Model
    HDF5 Groups
    HDF5 Datasets
    HDF5 Attributes
    The File as Written to Media

3. The HDF5 API
    Naming Conventions
    Include Files
    Programming Models
         Creating an HDF5 file
         Discarding objects
         Writing a dataset to a new file
         Getting information about a dataset
         Reading/writing a portion of a dataset
         Selecting hyperslabs
         Selecting of independent points
         Creating compound datatypes

   3. The HDF5 API (continued)
    Programming Models (continued)
         Creating/writing extendible and
                  chunked datasets
         Working with groups
         Working with attributes
         Working with references to objects
         Working with references to dataset
                  regions

4. Example Codes
         1: Creating and writing a dataset
         2. Reading a hyperslab
         3. Writing selected data
         4. Working with compound datatypes
         5. Creating and writing an extendible
                  dataset
         6. Reading data
         7. Creating groups
         8. Writing and reading attributes
         9. Creating and writing references
                  to objects
         10. Reading references to objects
         11. Creating and writing references
                  to dataset regions
         12. Reading references to dataset
                  regions


1. What Is HDF5?

HDF5 is a completely new Hierarchical Data Format product consisting of a data format specification and a supporting library implementation. HDF5 is designed to address some of the limitations of the older HDF product and to address current and anticipated requirements of modern systems and applications. 1

We urge you to look at HDF5, the format and the library, and give us feedback on what you like or do not like about it, and what features you would like to see added to it.

Why HDF5? The development of HDF5 is motivated by a number of limitations in the older HDF format and library. Some of these limitations are:

HDF5 includes the following improvements.

1. Note that HDF and HDF5 are two different products. HDF is a data format first developed in the 1980s and currently in Release 4.x (HDF Release 4.x). HDF5 is a new data format first released in Beta in 1998 and designed to better meet the ever-increasing demands of scientific computing and to take better advantage of the ever-increasing capabilities of computing systems. HDF5 is currently in Release 1.x (HDF5 Release 1.x).

Limitations of the Current Release

This release includes the basic functionality that was planned for the HDF5 library. However, the library does not implement all of the features detailed in the format and API specifications. Here is a listing of some of the limitations of the current release:

Changes in the Current Release

A detailed list of changes in HDF5 since the last release, HDF5 Release 1.0, can be found in the file hdf5/RELEASE in the source code installation. At a higher level, those changes include:

The changes in bugfix releases, numbered Release 1.2.x, will be listed in the RELEASE, HISTORY, and README files distributed with the source code.

The changes as HDF5 has evolved from the first Alpha release to the present are summarized in the file hdf5/HISTORY in the source code installation.

(Return to TOC)


2. HDF5 File Organization and Data Model

HDF5 files are organized in a hierarchical structure, with two primary structures: groups and datasets.

Working with groups and group members is similar in many ways to working with directories and files in UNIX. As with UNIX directories and files, objects in an HDF5 file are often described by giving their full (or absolute) path names.

/ signifies the root group.
/foo signifies a member of the root group called foo.
/foo/zoo signifies a member of the group foo, which in turn is a member of the root group.

Any HDF5 group or dataset may have an associated attribute list. An HDF5 attribute is a user-defined HDF5 structure that provides extra information about an HDF5 object. Attributes are described in more detail below.

HDF5 Groups

An HDF5 group is a structure containing zero or more HDF5 objects. A group has two parts:

HDF5 Datasets

A dataset is stored in a file in two parts: a header and a data array.

The header contains information that is needed to interpret the array portion of the dataset, as well as metadata (or pointers to metadata) that describes or annotates the dataset. Header information includes the name of the object, its dimensionality, its number-type, information about how the data itself is stored on disk, and other information used by the library to speed up access to the dataset or maintain the file's integrity.

There are four essential classes of information in any header: name, datatype, dataspace, and storage layout:

Name. A dataset name is a sequence of alphanumeric ASCII characters.

Datatype. HDF5 allows one to define many different kinds of datatypes. There are two categories of datatypes: atomic datatypes and compound datatypes. Atomic datatypes can also be system-specific, or NATIVE, and all datatypes can be named:

Atomic datatypes include integers and floating-point numbers. Each atomic type belongs to a particular class and has several properties: size, order, precision, and offset. In this introduction, we consider only a few of these properties.

Atomic classes include integer, float, date and time, string, bit field, and opaque. (Note: Only integer, float and string classes are available in the current implementation.)

Properties of integer types include size, order (endian-ness), and signed-ness (signed/unsigned).

Properties of float types include the size and location of the exponent and mantissa, and the location of the sign bit.

The datatypes that are supported in the current implementation are:

NATIVE datatypes. Although it is possible to describe nearly any kind of atomic datatype, most applications will use predefined datatypes that are supported by their compiler. In HDF5 these are called native datatypes. NATIVE datatypes are C-like datatypes that are generally supported by the hardware of the machine on which the library was compiled. In order to be portable, applications should almost always use the NATIVE designation to describe data values in memory.

The NATIVE architecture has base names which do not follow the same rules as the others. Instead, native type names are similar to the C type names. The following figure shows several examples.

Examples of Native Datatypes and Corresponding C Types

Example

Corresponding C Type

H5T_NATIVE_CHAR signed char
H5T_NATIVE_UCHAR unsigned char
H5T_NATIVE_SHORT short
H5T_NATIVE_USHORT unsigned short
H5T_NATIVE_INT int
H5T_NATIVE_UINT unsigned
H5T_NATIVE_LONG long
H5T_NATIVE_ULONG unsigned long
H5T_NATIVE_LLONG long long
H5T_NATIVE_ULLONG unsigned long long
H5T_NATIVE_FLOAT float
H5T_NATIVE_DOUBLE double
H5T_NATIVE_LDOUBLE long double
H5T_NATIVE_HSIZE hsize_t
H5T_NATIVE_HSSIZE hssize_t
H5T_NATIVE_HERR herr_t
H5T_NATIVE_HBOOL hbool_t

See Datatypes in the HDF User’s Guide for further information.

A compound datatype is one in which a collection of several datatypes are represented as a single unit, a compound datatype, similar to a struct in C. The parts of a compound datatype are called members. The members of a compound datatype may be of any datatype, including another compound datatype. It is possible to read members from a compound type without reading the whole type.

Named datatypes. Normally each dataset has its own datatype, but sometimes we may want to share a datatype among several datasets. This can be done using a named datatype. A named datatype is stored in the file independently of any dataset, and referenced by all datasets that have that datatype. Named datatypes may have an associated attributes list. See Datatypes in the HDF User’s Guide for further information.

Dataspace. A dataset dataspace describes the dimensionality of the dataset. The dimensions of a dataset can be fixed (unchanging), or they may be unlimited, which means that they are extendible (i.e. they can grow larger).

Properties of a dataspace consist of the rank (number of dimensions) of the data array, the actual sizes of the dimensions of the array, and the maximum sizes of the dimensions of the array. For a fixed-dimension dataset, the actual size is the same as the maximum size of a dimension. When a dimension is unlimited, the maximum size is set to the value H5P_UNLIMITED. (An example below shows how to create extendible datasets.)

A dataspace can also describe portions of a dataset, making it possible to do partial I/O operations on selections. Selection is supported by the dataspace interface (H5S). Given an n-dimensional dataset, there are currently four ways to do partial selection:

  1. Select a logically contiguous n-dimensional hyperslab.
  2. Select a non-contiguous hyperslab consisting of elements or blocks of elements (hyperslabs) that are equally spaced.
  3. Select a union of hyperslabs.
  4. Select a list of independent points.

Since I/O operations have two end-points, the raw data transfer functions require two dataspace arguments: one describes the application memory dataspace or subset thereof, and the other describes the file dataspace or subset thereof.

See Dataspaces in the HDF User’s Guide for further information.

Storage layout. The HDF5 format makes it possible to store data in a variety of ways. The default storage layout format is contiguous, meaning that data is stored in the same linear way that it is organized in memory. Two other storage layout formats are currently defined for HDF5: compact, and chunked. In the future, other storage layouts may be added.

Compact storage is used when the amount of data is small and can be stored directly in the object header. (Note: Compact storage is not supported in this release.)

Chunked storage involves dividing the dataset into equal-sized "chunks" that are stored separately. Chunking has three important benefits.

  1. It makes it possible to achieve good performance when accessing subsets of the datasets, even when the subset to be chosen is orthogonal to the normal storage order of the dataset.
  2. It makes it possible to compress large datasets and still achieve good performance when accessing subsets of the dataset.
  3. It makes it possible efficiently to extend the dimensions of a dataset in any direction.

See Datasets and Dataset Chunking Issues in the HDF User’s Guide for further information. We particularly encourage you to read Dataset Chunking Issues since the issue is complex and beyond the scope of this document.

HDF5 Attributes

Attributes are small named datasets that are attached to primary datasets, groups, or named datatypes. Attributes can be used to describe the nature and/or the intended usage of a dataset or group. An attribute has two parts: (1) a name and (2) a value. The value part contains one or more data entries of the same datatype.

The Attribute API (H5A) is used to read or write attribute information. When accessing attributes, they can be identified by name or by an index value. The use of an index value makes it possible to iterate through all of the attributes associated with a given object.

The HDF5 format and I/O library are designed with the assumption that attributes are small datasets. They are always stored in the object header of the object they are attached to. Because of this, large datasets should not be stored as attributes. How large is "large" is not defined by the library and is up to the user's interpretation. (Large datasets with metadata can be stored as supplemental datasets in a group with the primary dataset.)

See Attributes in the HDF User’s Guide for further information.

The File as Written to Media

For those who are interested, this section takes a look at the low-level elements of the file as the file is written to disk (or other storage media) and the relation of those low-level elements to the higher level elements with which users typically are more familiar. The HDF5 API generally exposes only the high-level elements to the user; the low-level elements are often hidden. The rest of this Introduction does not assume an understanding of this material.

The format of an HDF5 file on disk encompasses several key ideas of the HDF4 and AIO file formats as well as addressing some shortcomings therein. The new format is more self-describing than the HDF4 format and is more uniformly applied to data objects in the file.

HDF5 Groups
 
Figure 1: Relationships among the HDF5 root group, other groups, and objects
 

An HDF5 file appears to the user as a directed graph. The nodes of this graph are the higher-level HDF5 objects that are exposed by the HDF5 APIs:

At the lowest level, as information is actually written to the disk, an HDF5 file is made up of the following objects:

The HDF5 library uses these lower-level objects to represent the higher-level objects that are then presented to the user or to applications through the APIs. For instance, a group is an object header that contains a message that points to a local heap and to a B-tree which points to symbol nodes. A dataset is an object header that contains messages that describe datatype, space, layout, filters, external files, fill value, etc with the layout message pointing to either a raw data chunk or to a B-tree that points to raw data chunks.

See the HDF5 File Format Specification for further information.

(Return to TOC)


3. The HDF5 Applications Programming Interface (API)

The current HDF5 API is implemented only in C. The API provides routines for creating HDF5 files, creating and writing groups, datasets, and their attributes to HDF5 files, and reading groups, datasets and their attributes from HDF5 files.

Naming conventions

All C routines in the HDF 5 library begin with a prefix of the form H5*, where * is a single letter indicating the object on which the operation is to be performed:

Include Files

There are a number definitions and declarations that should be included with any HDF5 program. These definitions and declarations are contained in several include files. The main include file is hdf5.h. This file includes all of the other files that your program is likely to need. Be sure to include hdf5.h in any program that uses the HDF5 library.

Programming Models

In this section we describe how to program some basic operations on files, including how to

How to create an HDF5 file

This programming model shows how to create a file and also how to close the file.

  1. Create the file.
  2. Close the file.

The following code fragment implements the specified model. If there is a possibility that the file already exists, the user must add the flag H5ACC_TRUNC to the access mode to overwrite the previous file's information.

hid_t       file;                          /* identifier */
/*
* Create a new file using H5ACC_TRUNC access,
* default file creation properties, and default file
* access properties.
* Then close the file.
*/
file = H5Fcreate(FILE, H5ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
status = H5Fclose(file); 
 

How to create and initialize the essential components of a dataset for writing to a file

Recall that datatypes and dimensionality (dataspace) are independent objects, which are created separately from any dataset that they might be attached to. Because of this the creation of a dataset requires, at a minimum, separate definitions of datatype, dimensionality, and dataset. Hence, to create a dataset the following steps need to be taken:

  1. Create and initialize a dataspace for the dataset to be written.
  2. Define the datatype for the dataset to be written.
  3. Create and initialize the dataset itself.

The following code illustrates the creation of these three components of a dataset object.

hid_t    dataset, datatype, dataspace;   /* declare identifiers */

/* 
 * Create dataspace: Describe the size of the array and 
 * create the data space for fixed size dataset. 
 */
dimsf[0] = NX;
dimsf[1] = NY;
dataspace = H5Screate_simple(RANK, dimsf, NULL); 
/*
 * Define datatype for the data in the file.
 * We will store little endian integer numbers.
 */
datatype = H5Tcopy(H5T_NATIVE_INT);
status = H5Tset_order(datatype, H5T_ORDER_LE);
/*
 * Create a new dataset within the file using defined 
 * dataspace and datatype and default dataset creation
 * properties.
 * NOTE: H5T_NATIVE_INT can be used as datatype if conversion
 * to little endian is not needed.
 */
dataset = H5Dcreate(file, DATASETNAME, datatype, dataspace, H5P_DEFAULT);

How to discard objects when they are no longer needed

The datatype, dataspace and dataset objects should be released once they are no longer needed by a program. Since each is an independent object, the must be released (or closed) separately. The following lines of code close the datatype, dataspace, and datasets that were created in the preceding section.

H5Tclose(datatype);

H5Dclose(dataset);

H5Sclose(dataspace);

How to write a dataset to a new file

Having defined the datatype, dataset, and dataspace parameters, you write out the data with a call to H5Dwrite.

/*
* Write the data to the dataset using default transfer
* properties.
*/
status = H5Dwrite(dataset, H5T_NATIVE_INT, H5S_ALL, H5S_ALL,
	  H5P_DEFAULT, data);

The third and fourth parameters of H5Dwrite in the example describe the dataspaces in memory and in the file, respectively. They are set to the value H5S_ALL to indicate that an entire dataset is to be written. In a later section we look at how we would access a portion of a dataset.

Example 1 contains a program that creates a file and a dataset, and writes the dataset to the file.

Reading is analogous to writing. If, in the previous example, we wish to read an entire dataset, we would use the same basic calls with the same parameters. Of course, the routine H5Dread would replace H5Dwrite.

Getting information about a dataset

Although reading is analogous to writing, it is often necessary to query a file to obtain information about a dataset. For instance, we often need to know about the datatype associated with a dataset, as well dataspace information (e.g. rank and dimensions). There are several "get" routines for obtaining this information. The following code segment illustrates how we would get this kind of information:

/*
* Get datatype and dataspace identifiers and then query
* dataset class, order, size, rank and dimensions.
*/

datatype  = H5Dget_type(dataset);     /* datatype identifier */ 
class     = H5Tget_class(datatype);
if (class == H5T_INTEGER) printf("Data set has INTEGER type \n");
order     = H5Tget_order(datatype);
if (order == H5T_ORDER_LE) printf("Little endian order \n");

size  = H5Tget_size(datatype);
printf(" Data size is %d \n", size);

dataspace = H5Dget_space(dataset);    /* dataspace identifier */
rank      = H5Sget_simple_extent_ndims(dataspace);
status_n  = H5Sget_simple_extent_dims(dataspace, dims_out);
printf("rank %d, dimensions %d x %d \n", rank, dims_out[0], dims_out[1]);

Reading and writing a portion of a dataset

In the previous discussion, we describe how to access an entire dataset with one write (or read) operation. HDF5 also supports access to portions (or selections) of a dataset in one read/write operation. Currently selections are limited to hyperslabs, their unions, and the lists of independent points. Both types of selection will be discussed in the following sections. Several sample cases of selection reading/writing are shown on the following figure.

In example (a) a single hyperslab is read from the midst of a two-dimensional array in a file and stored in the corner of a smaller two-dimensional array in memory. In (b) a regular series of blocks is read from a two-dimensional array in the file and stored as a contiguous sequence of values at a certain offset in a one-dimensional array in memory. In (c) a sequence of points with no regular pattern is read from a two-dimensional array in a file and stored as a sequence of points with no regular pattern in a three-dimensional array in memory. In (d) a union of hyperslabs in the file dataspace is read and the data is stored in another union of hyperslabs in the memory dataspace.

As these examples illustrate, whenever we perform partial read/write operations on the data, the following information must be provided: file dataspace, file dataspace selection, memory dataspace and memory dataspace selection. After the required information is specified, actual read/write operation on the portion of data is done in a single call to the HDF5 read/write functions H5Dread(write).

Selecting hyperslabs

Hyperslabs are portions of datasets. A hyperslab selection can be a logically contiguous collection of points in a dataspace, or it can be regular pattern of points or blocks in a dataspace. The following picture illustrates a selection of regularly spaced 3x2 blocks in an 8x12 dataspace.

Hyperslab selection
 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

                       
 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

                       

Four parameters are required to describe a completely general hyperslab. Each parameter is an array whose rank is the same as that of the dataspace:

In what order is data copied? When actual I/O is performed data values are copied by default from one dataspace to another in so-called row-major, or C order. That is, it is assumed that the first dimension varies slowest, the second next slowest, and so forth.

Example without strides or blocks. Suppose we want to read a 3x4 hyperslab from a dataset in a file beginning at the element <1,2> in the dataset. In order to do this, we must create a dataspace that describes the overall rank and dimensions of the dataset in the file, as well as the position and size of the hyperslab that we are extracting from that dataset. The following code illustrates the selection of the hyperslab in the file dataspace.

/* 
* Define file dataspace.
*/
dataspace = H5Dget_space(dataset);    /* dataspace identifier */
rank      = H5Sget_simple_extent_ndims(dataspace);
status_n  = H5Sget_simple_extent_dims(dataspace, dims_out, NULL);

/* 
* Define hyperslab in the dataset. 
*/
offset[0] = 1;
offset[1] = 2;
count[0]  = 3;
count[1]  = 4;
status = H5Sselect_hyperslab(dataspace, H5S_SELECT_SET, offset, NULL, 
         count, NULL);

This describes the dataspace from which we wish to read. We need to define the dataspace in memory analogously. Suppose, for instance, that we have in memory a 3 dimensional 7x7x3 array into which we wish to read the 3x4 hyperslab described above beginning at the element <3,0,0>. Since the in-memory dataspace has three dimensions, we have to describe the hyperslab as an array with three dimensions, with the last dimension being 1: <3,4,1>.

Notice that we must describe two things: the dimensions of the in-memory array, and the size and position of the hyperslab that we wish to read in. The following code illustrates how this would be done.

/*
* Define memory dataspace.
*/
dimsm[0] = 7;
dimsm[1] = 7;
dimsm[2] = 3;
memspace = H5Screate_simple(RANK_OUT,dimsm,NULL);   

/* 
* Define memory hyperslab. 
*/
offset_out[0] = 3;
offset_out[1] = 0;
offset_out[2] = 0;
count_out[0]  = 3;
count_out[1]  = 4;
count_out[2]  = 1;
status = H5Sselect_hyperslab(memspace, H5S_SELECT_SET, offset_out, NULL, 
         count_out, NULL);

/*

Example 2 contains a complete program that performs these operations.

Example with strides and blocks. Consider the 8x12 dataspace described above, in which we selected eight 3x2 blocks. Suppose we wish to fill these eight blocks.

Hyperslab selection
 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

                       
 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

 

X

X

                       

This hyperslab has the following parameters: start=(0,1), stride=(4,3), count=(2,4), block=(3,2).

Suppose that the source dataspace in memory is this 50-element one dimensional array called vector:

A 50-element one dimensional array

-1

1

2

3

4

5

6

7

...

47

48

-1

The following code will write 48 elements from vector to our file dataset, starting with the second element in vector.

/* Select hyperslab for the dataset in the file, using 3x2 blocks, (4,3) stride
 * (2,4) count starting at the position (0,1).
 */
start[0]  = 0; start[1]  = 1;
stride[0] = 4; stride[1] = 3;
count[0]  = 2; count[1]  = 4;    
block[0]  = 3; block[1]  = 2;
ret = H5Sselect_hyperslab(fid, H5S_SELECT_SET, start, stride, count, block);

/*
 * Create dataspace for the first dataset.
 */
mid1 = H5Screate_simple(MSPACE1_RANK, dim1, NULL);

/*
 * Select hyperslab. 
 * We will use 48 elements of the vector buffer starting at the second element.
 * Selected elements are 1 2 3 . . . 48
 */
start[0]  = 1;
stride[0] = 1;
count[0]  = 48;
block[0]  = 1;
ret = H5Sselect_hyperslab(mid1, H5S_SELECT_SET, start, stride, count, block);
 
/*
 * Write selection from the vector buffer to the dataset in the file.
 *
ret = H5Dwrite(dataset, H5T_NATIVE_INT, midd1, fid, H5P_DEFAULT, vector)

 

After these operations, the file dataspace will have the following values.

Hyperslab selection with assigned values
 

1

2

 

3

4

 

5

6

 

7

8

 

9

10

 

11

12

 

13

14

 

15

16

 

17

18

 

19

20

 

21

22

 

23

24

                       
 

25

26

 

27

28

 

29

30

 

31

32

 

33

34

 

35

36

 

37

38

 

39

40

 

41

42

 

43

44

 

45

46

 

47

48

                       

Notice that the values are inserted in the file dataset in row-major order.

Example 3 includes this code and other example code illustrating the use of hyperslab selection.

Selecting a list of independent points
A hyperslab specifies a regular pattern of elements in a dataset. It is also possible to specify a list of independent elements to read or write using the function H5Sselect_elements. Suppose, for example, that we wish to write the values 53, 59, 61, 67 to the following elements of the 8x12 array used in the previous example: (0,0), (3,3), (3,5), and (5,6). The following code selects the points and writes them to the dataset:
#define FSPACE_RANK      2    /* Dataset rank as it is stored in the file */
#define NPOINTS          4    /* Number of points that will be selected 
                                 and overwritten */ 
#define MSPACE2_RANK     1    /* Rank of the second dataset in memory */ 
#define MSPACE2_DIM      4    /* Dataset size in memory */ 

 
hsize_t dim2[] = {MSPACE2_DIM};       /* Dimension size of the second 
                                         dataset (in memory) */ 
int     values[] = {53, 59, 61, 67};  /* New values to be written */
hssize_t coord[NPOINTS][FSPACE_RANK]; /* Array to store selected points 
                                         from the file dataspace */ 

/*
 * Create dataspace for the second dataset.
 */
mid2 = H5Screate_simple(MSPACE2_RANK, dim2, NULL);

/*
 * Select sequence of NPOINTS points in the file dataspace.
 */
coord[0][0] = 0; coord[0][1] = 0;
coord[1][0] = 3; coord[1][1] = 3;
coord[2][0] = 3; coord[2][1] = 5;
coord[3][0] = 5; coord[3][1] = 6;

ret = H5Sselect_elements(fid, H5S_SELECT_SET, NPOINTS, 
                         (const hssize_t **)coord);

/*
 * Write new selection of points to the dataset.
 */
ret = H5Dwrite(dataset, H5T_NATIVE_INT, mid2, fid, H5P_DEFAULT, values);   

 

After these operations, the file dataspace will have the following values:

Hyperslab selection with an overlay of independent points

53

1

2

 

3

4

 

5

6

 

7

8

 

9

10

 

11

12

 

13

14

 

15

16

 

17

18

 

19

20

 

21

22

 

23

24

     

59

 

61

           
 

25

26

 

27

28

 

29

30

 

31

32

 

33

34

 

35

36

67

37

38

 

39

40

 

41

42

 

43

44

 

45

46

 

47

48

                       

Example 3 contains a complete program that performs these subsetting operations.

Selecting a union of hyperslabs
The HDF5 Library allows the user to select a union of hyperslabs and write or read the selection into another selection. The shapes of the two selections may differ, but the number of elements must be equal.

Suppose that we want to read two overlapping hyperslabs from the dataset written in the previous example into a union of hyperslabs in the memory dataset. This exercise is illustrated in the two figures immediately below. Note that the memory dataset has a different shape from the previously written dataset. Similarly, the selection in the memory dataset could have a different shape than the selected union of hyperslabs in the original file; for simplicity, we will preserve the selection's shape in this example.

Selection of a union of hyperslabs in a file dataset

53

1

2

 

3

4

 

5

6

 

7

8

 

9

10

 

11

12

 

13

14

 

15

16

 

17

18

 

19

20

 

21

22

 

23

24

     

59

 

61

           
 

25

26

 

27

28

 

29

30

 

31

32

 

33

34

 

35

36

67

37

38

 

39

40

 

41

42

 

43

44

 

45

46

 

47

48

                       
(Note: The above table highlights hyperslab selections with green, blue, and yellow
shading. This shading may not appear properly in black-and-white printed copies.)

Selection of a union of hyperslabs in a memory dataset
Blank cells in this figure actually contain values written when the dataset was initialized.

10

 

11

12

         

18

 

19

20

 

21

22

   
 

59

 

61

         
   

27

28

 

29

30

   
   

35

36

67

37

38

   
   

43

44

 

45

46

   
                 
                 
(Note: The above table highlights hyperslab selections with green, blue, and yellow
shading. This shading may not appear properly in black-and-white printed copies.)

The following lines of code show the required steps.

First obtain the dataspace identifier for the dataset in the file.

    /*
     * Get dataspace of the open dataset.
     */  
    fid = H5Dget_space(dataset);
Then select the hyperslab with the size 3x4 and the left upper corner at the position (1,2):
    /*
     * Select first hyperslab for the dataset in the file. The following
     * elements are selected:
     *                     10  0 11 12
     *                     18  0 19 20
     *                      0 59  0 61
     *   
     */ 
    start[0] = 1; start[1] = 2;
    block[0] = 1; block[1] = 1;
    stride[0] = 1; stride[1] = 1;
    count[0]  = 3; count[1]  = 4;
    ret = H5Sselect_hyperslab(fid, H5S_SELECT_SET, start, stride, count, block); 
Now select the second hyperslab with the size 6x5 at the position (2,4), and create the union with the first hyperslab.
    /*
     * Add second selected hyperslab to the selection.
     * The following elements are selected:
     *                    19 20  0 21 22
     *                     0 61  0  0  0
     *                    27 28  0 29 30
     *                    35 36 67 37 38
     *                    43 44  0 45 46
     *                     0  0  0  0  0
     * Note that two hyperslabs overlap. Common elements are:
     *                                              19 20
     *                                               0 61
     */
    start[0] = 2; start[1] = 4;
    block[0] = 1; block[1] = 1;
    stride[0] = 1; stride[1] = 1;
    count[0]  = 6; count[1]  = 5;
    ret = H5Sselect_hyperslab(fid, H5S_SELECT_OR, start, stride, count, block);
Note that when we add the selected hyperslab to the union, the second argument to the H5Sselect_hyperslab function has to be H5S_SELECT_OR instead of H5S_SELECT_SET. Using H5S_SELECT_SET would reset the selection to the second hyperslab.

Now define the memory dataspace and select the union of the hyperslabs in the memory dataset.

    /*
     * Create memory dataspace.
     */
    mid = H5Screate_simple(MSPACE_RANK, mdim, NULL);
     
    /*
     * Select two hyperslabs in memory. Hyperslabs has the same
     * size and shape as the selected hyperslabs for the file dataspace.
     */
    start[0] = 0; start[1] = 0;
    block[0] = 1; block[1] = 1;
    stride[0] = 1; stride[1] = 1;
    count[0]  = 3; count[1]  = 4;
    ret = H5Sselect_hyperslab(mid, H5S_SELECT_SET, start, stride, count, block);     
    start[0] = 1; start[1] = 2;
    block[0] = 1; block[1] = 1;
    stride[0] = 1; stride[1] = 1;
    count[0]  = 6; count[1]  = 5;
    ret = H5Sselect_hyperslab(mid, H5S_SELECT_OR, start, stride, count, block);
Finally we can read the selected data from the file dataspace to the selection in memory with one call to the H5Dread function.
    ret = H5Dread(dataset, H5T_NATIVE_INT, mid, fid, H5P_DEFAULT, matrix_out);

Example 3 includes this code along with the previous selection example.

Creating compound datatypes

Properties of compound datatypes. A compound datatype is similar to a struct in C or a common block in Fortran. It is a collection of one or more atomic types or small arrays of such types. To create and use of a compound datatype you need to refer to various properties of the data compound datatype:

Properties of members of a compound datatype are defined when the member is added to the compound type and cannot be subsequently modified.

Defining compound datatypes. Compound datatypes must be built out of other datatypes. First, one creates an empty compound datatype and specifies its total size. Then members are added to the compound datatype in any order.

Member names. Each member must have a descriptive name, which is the key used to uniquely identify the member within the compound datatype. A member name in an HDF5 datatype does not necessarily have to be the same as the name of the corresponding member in the C struct in memory, although this is often the case. Nor does one need to define all members of the C struct in the HDF5 compound datatype (or vice versa).

Offsets. Usually a C struct will be defined to hold a data point in memory, and the offsets of the members in memory will be the offsets of the struct members from the beginning of an instance of the struct. The library defines the macro to compute the offset of a member within a struct:
  HOFFSET(s,m)

This macro computes the offset of member m within a struct variable s.

Here is an example in which a compound datatype is created to describe complex numbers whose type is defined by the complex_t struct.

typedef struct {
   double re;   /*real part */
   double im;   /*imaginary part */
} complex_t;

complex_t tmp;  /*used only to compute offsets */
hid_t complex_id = H5Tcreate (H5T_COMPOUND, sizeof tmp);
H5Tinsert (complex_id, "real", HOFFSET(tmp,re),
           H5T_NATIVE_DOUBLE);
H5Tinsert (complex_id, "imaginary", HOFFSET(tmp,im),
           H5T_NATIVE_DOUBLE);

Example 4 shows how to create a compound datatype, write an array that has the compound datatype to the file, and read back subsets of the members.

Creating and writing extendible and chunked datasets

An extendible dataset is one whose dimensions can grow. In HDF5, it is possible to define a dataset to have certain initial dimensions, then later to increase the size of any of the initial dimensions.

For example, you can create and store the following 3x3 HDF5 dataset:

     1 1 1
     1 1 1 
     1 1 1 

then later to extend this into a 10x3 dataset by adding 7 rows, such as this:

     1 1 1 
     1 1 1 
     1 1 1 
     2 2 2
     2 2 2
     2 2 2
     2 2 2
     2 2 2
     2 2 2
     2 2 2

then further extend it to a 10x5 dataset by adding two columns, such as this:

     1 1 1 3 3 
     1 1 1 3 3 
     1 1 1 3 3 
     2 2 2 3 3
     2 2 2 3 3
     2 2 2 3 3
     2 2 2 3 3
     2 2 2 3 3
     2 2 2 3 3
     2 2 2 3 3

HDF 5 requires you to use chunking in order to define extendible datasets. Chunking makes it possible to extend datasets efficiently, without having to reorganize storage excessively.

The following operations are required in order to write an extendible dataset:

  1. Declare the dataspace of the dataset to have unlimited dimensions for all dimensions that might eventually be extended.
  2. Set dataset creation properties to enable chunking and create a dataset.
  3. Extend the size of the dataset.

For example, suppose we wish to create a dataset similar to the one shown above. We want to start with a 3x3 dataset, then later extend it in both directions.

Declaring unlimited dimensions. We could declare the dataspace to have unlimited dimensions with the following code, which uses the predefined constant H5S_UNLIMITED to specify unlimited dimensions.

hsize_t dims[2] = { 3, 3}; /* dataset dimensions
at the creation time */ 
hsize_t maxdims[2] = {H5S_UNLIMITED, H5S_UNLIMITED};
/*
 * Create the data space with unlimited dimensions. 
 */
dataspace = H5Screate_simple(RANK, dims, maxdims); 

Enabling chunking. We can then set the dataset storage layout properties to enable chunking. We do this using the routine H5Pset_chunk:

hid_t cparms; 
hsize_t chunk_dims[2] ={2, 5};
/* 
 * Modify dataset creation properties to enable chunking.
 */
cparms = H5Pcreate (H5P_DATASET_CREATE);
status = H5Pset_chunk( cparms, RANK, chunk_dims);
Then create a dataset.
/*
 * Create a new dataset within the file using cparms
 * creation properties.
 */
dataset = H5Dcreate(file, DATASETNAME, H5T_NATIVE_INT, dataspace,
                 cparms);

Extending dataset size. Finally, when we want to extend the size of the dataset, we invoke H5Dextend to extend the size of the dataset. In the following example, we extend the dataset along the first dimension, by seven rows, so that the new dimensions are <10,3>:

/*
 * Extend the dataset. Dataset becomes 10 x 3.
 */
dims[0] = dims[0] + 7;
size[0] = dims[0]; 
size[1] = dims[1]; 
status = H5Dextend (dataset, size);

 

Example 5 shows how to create a 3x3 extendible dataset, write the dataset, extend the dataset to 10x3, write the dataset again, extend it again to 10x5, write the dataset again.

Example 6 shows how to read the data written by Example 5.

Working with groups in a file

Groups provide a mechanism for organizing meaningful and extendible sets of datasets within an HDF5 file. The H5G API contains routines for working with groups.

Creating a group. To create a group, use H5Gcreate. For example, the following code creates a group called Data in the root group.

 /*
  *  Create a group in the file.
  */
 grp = H5Gcreate(file, "/Data", 0);
A group may be created in another group by providing the absolute name of the group to the H5Gcreate function or by specifying its location. For example, to create the group Data_new in the Data group, one can use the following sequence of calls:
 /*
  * Create group "Data_new" in the group "Data" by specifying
  * absolute name of the group.
  */
 grp_new = H5Gcreate(file, "/Data/Data_new", 0);
or
 /*
  * Create group "Data_new" in the "Data" group.
  */
 grp_new = H5Gcreate(grp, "Data_new", 0);
Note that the group identifier grp is used as the first parameter in the H5Gcreate function when the relative name is provided.

The third parameter in H5Gcreate optionally specifies how much file space to reserve to store the names that will appear in this group. If a non-positive value is supplied, then a default size is chosen.

H5Gclose closes the group and releases the group identifier.

Creating a dataset in a particular group. As with groups, a dataset can be created in a particular group by specifying its absolute name as illustrated in the following example:

 
 /*
  * Create the dataset "Compressed_Data" in the group using the 
  * absolute name. The dataset creation property list is modified 
  * to use GZIP compression with the compression effort set to 6.
  * Note that compression can be used only when the dataset is 
  * chunked.
  */
 dims[0] = 1000;
 dims[1] = 20;
 cdims[0] = 20;
 cdims[1] = 20;
 dataspace = H5Screate_simple(RANK, dims, NULL);
 plist     = H5Pcreate(H5P_DATASET_CREATE);
             H5Pset_chunk(plist, 2, cdims);
             H5Pset_deflate( plist, 6);
 dataset = H5Dcreate(file, "/Data/Compressed_Data", H5T_NATIVE_INT,
                     dataspace, plist);
A relative dataset name may also be used when a dataset is created. First obtain the identifier of the group in which the dataset is to be created. Then create the dataset with H5Dcreate as illustrated in the following example:
 /* 
  * Open the group.
  */
 grp = H5Gopen(file, "Data");

 /*
  * Create the dataset "Compressed_Data" in the "Data" group
  * by providing a group identifier and a relative dataset 
  * name as parameters to the H5Dcreate function.
  */
 dataset = H5Dcreate(grp, "Compressed_Data", H5T_NATIVE_INT,
                     dataspace, plist);

Accessing an object in a group. Any object in a group can be accessed by its absolute or relative name. The following lines of code show how to use the absolute name to access the dataset Compressed_Data in the group Data created in the examples above:

  /*
   * Open the dataset "Compressed_Data" in the "Data" group. 
   */
  dataset = H5Dopen(file, "/Data/Compressed_Data");
The same dataset can be accessed in another manner. First access the group to which the dataset belongs, then open the dataset.
  /*
   * Open the group "data" in the file.
   */
  grp  = H5Gopen(file, "Data");
 
  /*
   * Access the "Compressed_Data" dataset in the group.
   */
  dataset = H5Dopen(grp, "Compressed_Data");

Example 7 shows how to create a group in a file and a dataset in a group. It uses the iterator function H5Giterate to find the names of the objects in the root group, and H5Glink and H5Gunlink to create a new group name and delete the original name.

Working with attributes

Think of an attribute as a small datasets that is attached to a normal dataset or group. The H5A API contains routines for working with attributes. Since attributes share many of the characteristics of datasets, the programming model for working with attributes is analogous in many ways to the model for working with datasets. The primary differences are that an attribute must be attached to a dataset or a group, and subsetting operations cannot be performed on attributes.

To create an attribute belonging to a particular dataset or group, first create a dataspace for the attribute with the call to H5Screate, then create the attribute using H5Acreate. For example, the following code creates an attribute called Integer_attribute that is a member of a dataset whose identifier is dataset. The attribute identifier is attr2. H5Awrite then sets the value of the attribute of that of the integer variable point. H5Aclose then releases the attribute identifier.

int point = 1;                         /* Value of the scalar attribute */ 

/*
 * Create scalar attribute.
 */
aid2  = H5Screate(H5S_SCALAR);
attr2 = H5Acreate(dataset, "Integer attribute", H5T_NATIVE_INT, aid2,
                  H5P_DEFAULT);

/*
 * Write scalar attribute.
 */
ret = H5Awrite(attr2, H5T_NATIVE_INT, &point); 

/*
 * Close attribute dataspace.
 */
ret = H5Sclose(aid2); 

/*
 * Close attribute.
 */
ret = H5Aclose(attr2); 

 

To read a scalar attribute whose name and datatype are known, first open the attribute using H5Aopen_name, then use H5Aread to get its value. For example the following reads a scalar attribute called Integer_attribute whose datatype is a native integer, and whose parent dataset has the identifier dataset.

/*
 * Attach to the scalar attribute using attribute name, then read and 
 * display its value.
 */
attr = H5Aopen_name(dataset,"Integer attribute");
ret  = H5Aread(attr, H5T_NATIVE_INT, &point_out);
printf("The value of the attribute \"Integer attribute\" is %d \n", point_out); 
ret =  H5Aclose(attr);

Reading an attribute whose characteristics are not known. It may be necessary to query a file to obtain information about an attribute, namely its name, datatype, rank and dimensions. The following code opens an attribute by its index value using H5Aopen_index, then reads in information about its datatype.

/*
 * Attach to the string attribute using its index, then read and display the value.
 */
attr =  H5Aopen_idx(dataset, 2);
atype = H5Tcopy(H5T_C_S1);
        H5Tset_size(atype, 4);
ret   = H5Aread(attr, atype, string_out);
printf("The value of the attribute with the index 2 is %s \n", string_out);

In practice, if the characteristics of attributes are not known, the code involved in accessing and processing the attribute can be quite complex. For this reason, HDF5 includes a function called H5Aiterate, which applies a user-supplied function to each of a set of attributes. The user-supplied function can contain the code that interprets, accesses and processes each attribute.

Example 8 illustrates the use of the H5Aiterate function, as well as the other attribute examples described above.

Working with references to objects

In HDF5, objects (i.e. groups, datasets, and named datatypes) are usually accessed by name. This access method was discussed in previous sections. There is another way to access stored objects -- by reference.

An object reference is based on the relative file address of the object header in the file and is constant for the life of the object. Once a reference to an object is created and stored in a dataset in the file, it can be used to dereference the object it points to. References are handy for creating a file index or for grouping related objects by storing references to them in one dataset.

Creating and Storing References to Objects
The following steps are involved in creating and storing file references to objects:
  1. Create the objects or open them if they already exist in the file.
  2. Create a dataset to store the objects' references.
  3. Create and store references to the objects in a buffer.
  4. Write a buffer with the references to the dataset.
Programming Example
Description: The example below [also Example 9] creates a group and two datasets and a named datatype in the group. References to these four objects are stored in the dataset in the root group.

#include <hdf5.h>

#define FILE1   "trefer1.h5"

/* 1-D dataset with fixed dimensions */
#define SPACE1_NAME  "Space1"
#define SPACE1_RANK	1
#define SPACE1_DIM1	4

/* 2-D dataset with fixed dimensions */
#define SPACE2_NAME  "Space2"
#define SPACE2_RANK	2
#define SPACE2_DIM1	10
#define SPACE2_DIM2	10

int 
main(void) {
    hid_t		fid1;		/* HDF5 File IDs		*/
    hid_t		dataset;	/* Dataset ID			*/
    hid_t		group;      /* Group ID             */
    hid_t		sid1;       /* Dataspace ID			*/
    hid_t		tid1;       /* Datatype ID			*/
    hsize_t		dims1[] = {SPACE1_DIM1};
    hobj_ref_t      *wbuf;      /* buffer to write to disk */
    int       *tu32;      /* Temporary pointer to int data */
    int        i;          /* counting variables */
    const char *write_comment="Foo!"; /* Comments for group */
    herr_t		ret;		/* Generic return value		*/

/* Compound datatype */
typedef struct s1_t {
    unsigned int a;
    unsigned int b;
    float c;
} s1_t;

    /* Allocate write buffers */
    wbuf=(hobj_ref_t *)malloc(sizeof(hobj_ref_t)*SPACE1_DIM1);
    tu32=malloc(sizeof(int)*SPACE1_DIM1);

    /* Create file */
    fid1 = H5Fcreate(FILE1, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

    /* Create dataspace for datasets */
    sid1 = H5Screate_simple(SPACE1_RANK, dims1, NULL);

    /* Create a group */
    group=H5Gcreate(fid1,"Group1",-1);

    /* Set group's comment */
    ret=H5Gset_comment(group,".",write_comment);

    /* Create a dataset (inside Group1) */
    dataset=H5Dcreate(group,"Dataset1",H5T_STD_U32LE,sid1,H5P_DEFAULT);

    for(i=0; i < SPACE1_DIM1; i++)
        tu32[i] = i*3;

    /* Write selection to disk */
    ret=H5Dwrite(dataset,H5T_NATIVE_INT,H5S_ALL,H5S_ALL,H5P_DEFAULT,tu32);

    /* Close Dataset */
    ret = H5Dclose(dataset);

    /* Create another dataset (inside Group1) */
    dataset=H5Dcreate(group,"Dataset2",H5T_NATIVE_UCHAR,sid1,H5P_DEFAULT);

    /* Close Dataset */
    ret = H5Dclose(dataset);

    /* Create a datatype to refer to */
    tid1 = H5Tcreate (H5T_COMPOUND, sizeof(s1_t));

    /* Insert fields */
    ret=H5Tinsert (tid1, "a", HOFFSET(s1_t,a), H5T_NATIVE_INT);

    ret=H5Tinsert (tid1, "b", HOFFSET(s1_t,b), H5T_NATIVE_INT);

    ret=H5Tinsert (tid1, "c", HOFFSET(s1_t,c), H5T_NATIVE_FLOAT);

    /* Save datatype for later */
    ret=H5Tcommit (group, "Datatype1", tid1);

    /* Close datatype */
    ret = H5Tclose(tid1);

    /* Close group */
    ret = H5Gclose(group);

    /* Create a dataset to store references */
    dataset=H5Dcreate(fid1,"Dataset3",H5T_STD_REF_OBJ,sid1,H5P_DEFAULT);

    /* Create reference to dataset */
    ret = H5Rcreate(&wbuf[0],fid1,"/Group1/Dataset1",H5R_OBJECT,-1);

    /* Create reference to dataset */
    ret = H5Rcreate(&wbuf[1],fid1,"/Group1/Dataset2",H5R_OBJECT,-1);

    /* Create reference to group */
    ret = H5Rcreate(&wbuf[2],fid1,"/Group1",H5R_OBJECT,-1);

    /* Create reference to named datatype */
    ret = H5Rcreate(&wbuf[3],fid1,"/Group1/Datatype1",H5R_OBJECT,-1);

    /* Write selection to disk */
    ret=H5Dwrite(dataset,H5T_STD_REF_OBJ,H5S_ALL,H5S_ALL,H5P_DEFAULT,wbuf);

    /* Close disk dataspace */
    ret = H5Sclose(sid1);
    
    /* Close Dataset */
    ret = H5Dclose(dataset);

    /* Close file */
    ret = H5Fclose(fid1);
    free(wbuf);
    free(tu32);
    return 0;
}

Remarks: File Contents: The contents of the trefer1.h5 file created by this example are as follows:

HDF5 "trefer1.h5" {
GROUP "/" {
   DATASET "Dataset3" {
      DATATYPE { H5T_REFERENCE }
      DATASPACE { SIMPLE ( 4 ) / ( 4 ) }
      DATA {
         DATASET 0:1696, DATASET 0:2152, GROUP 0:1320, DATATYPE 0:2268
      }
   }
   GROUP "Group1" {
      DATASET "Dataset1" {
         DATATYPE { H5T_STD_U32LE }
         DATASPACE { SIMPLE ( 4 ) / ( 4 ) }
         DATA {
            0, 3, 6, 9
         }
      }
      DATASET "Dataset2" {
         DATATYPE { H5T_STD_U8LE }
         DATASPACE { SIMPLE ( 4 ) / ( 4 ) }
         DATA {
            0, 0, 0, 0
         }
      }
      DATATYPE "Datatype1" {
         H5T_STD_I32BE "a";
         H5T_STD_I32BE "b";
         H5T_IEEE_F32BE "c";
      }
   }
}
}

Notice how the data in dataset Dataset3 is described. The two numbers with the colon in between represent a unique identifier of the object. These numbers are constant for the life of the object.
Reading References and Accessing Objects Using References
The following steps are involved:
  1. Open the dataset with the references and read them. The H5T_STD_REF_OBJ datatype must be used to describe the memory datatype.
  2. Use the read reference to obtain the identifier of the object the reference points to.
  3. Open the dereferenced object and perform the desired operations.
  4. Close all objects when the task is complete.
Programming Example
Description: The following example [also Example 10] below opens and reads dataset Dataset3 from the file created previously. Then the program dereferences the references to dataset Dataset1, the group and the named datatype, and opens those objects. The program reads and displays the dataset's data, the group's comment, and the number of members of the compound datatype.

#include <stdlib.h>
#include <hdf5.h>

#define FILE1   "trefer1.h5"

/* dataset with fixed dimensions */
#define SPACE1_NAME  "Space1"
#define SPACE1_RANK	1
#define SPACE1_DIM1	4

int 
main(void)
{
    hid_t		fid1;		/* HDF5 File IDs		*/
    hid_t		dataset,	/* Dataset ID			*/
                dset2;      /* Dereferenced dataset ID */
    hid_t		group;      /* Group ID             */
    hid_t		sid1;       /* Dataspace ID			*/
    hid_t		tid1;       /* Datatype ID			*/
    hobj_ref_t      *rbuf;      /* buffer to read from disk */
    int                *tu32;      /* temp. buffer read from disk */
    int        i;          /* counting variables */
    char read_comment[10];
    herr_t		ret;		/* Generic return value		*/

    /* Allocate read buffers */
    rbuf = malloc(sizeof(hobj_ref_t)*SPACE1_DIM1);
    tu32 = malloc(sizeof(int)*SPACE1_DIM1);

    /* Open the file */
    fid1 = H5Fopen(FILE1, H5F_ACC_RDWR, H5P_DEFAULT);

    /* Open the dataset */
    dataset=H5Dopen(fid1,"/Dataset3");

    /* Read selection from disk */
    ret=H5Dread(dataset,H5T_STD_REF_OBJ,H5S_ALL,H5S_ALL,H5P_DEFAULT,rbuf);

    /* Open dataset object */
    dset2 = H5Rdereference(dataset,H5R_OBJECT,&rbuf[0]);

    /* Check information in referenced dataset */
    sid1 = H5Dget_space(dset2);

    ret=H5Sget_simple_extent_npoints(sid1);

    /* Read from disk */
    ret=H5Dread(dset2,H5T_NATIVE_INT,H5S_ALL,H5S_ALL,H5P_DEFAULT,tu32);
    printf("Dataset data : \n");
     for (i=0; i < SPACE1_DIM1 ; i++) printf (" %d ", tu32[i]);
    printf("\n");
    printf("\n");

    /* Close dereferenced Dataset */
    ret = H5Dclose(dset2);

    /* Open group object */
    group = H5Rdereference(dataset,H5R_OBJECT,&rbuf[2]);

    /* Get group's comment */
    ret=H5Gget_comment(group,".",10,read_comment);
    printf("Group comment is %s \n", read_comment);
    printf(" \n");
    /* Close group */
    ret = H5Gclose(group);

    /* Open datatype object */
    tid1 = H5Rdereference(dataset,H5R_OBJECT,&rbuf[3]);

    /* Verify correct datatype */
    {
        H5T_class_t tclass;

        tclass= H5Tget_class(tid1);
        if ((tclass == H5T_COMPOUND))
           printf ("Number of compound datatype members is %d \n", H5Tget_nmembers(tid1)); 
    printf(" \n");
    }

    /* Close datatype */
    ret = H5Tclose(tid1);

    /* Close Dataset */
    ret = H5Dclose(dataset);

    /* Close file */
    ret = H5Fclose(fid1);

    /* Free memory buffers */
    free(rbuf);
    free(tu32);
    return 0;
}   

The output of this program is as follows:

Dataset data : 
 0  3  6  9 

Group comment is Foo! 
 
Number of compound datatype members is 3 
Remarks:

Working with references to dataset regions

A dataset region reference points to the dataset selection by storing the relative file address of the dataset header and the global heap offset of the referenced selection. The selection referenced is located by retrieving the coordinates of the areas in the selection from the global heap. This internal mechanism of storing and retrieving dataset selections is transparent to the user. A reference to the dataset selection (region) is constant for the life of the dataset.
Creating and Storing References to Dataset Regions
The following steps are involved in creating and storing references to the dataset regions:
  1. Create a dataset to store the dataset regions (selections).

  2. Create selections in the dataset(s). Dataset(s) should already exist in the file.

  3. Create references to the selections and store them in a buffer.

  4. Write references to the dataset regions in the file.

  5. Close all objects.
Programming Example
Description: The example below [also Example 11] creates a dataset in the file. Then it creates a dataset to store references to the dataset regions (selections). The first selection is a 6 x 6 hyperslab. The second selection is a point selection in the same dataset. References to both selections are created and stored in the buffer, and then written to the dataset in the file.

#include <stdlib.h>
#include <hdf5.h>

#define FILE2	"trefer2.h5"
#define SPACE1_NAME  "Space1"
#define SPACE1_RANK     1
#define SPACE1_DIM1     4

/* Dataset with fixed dimensions */
#define SPACE2_NAME  "Space2"
#define SPACE2_RANK	2
#define SPACE2_DIM1	10
#define SPACE2_DIM2	10

/* Element selection information */
#define POINT1_NPOINTS 10

int
main(void)
{
    hid_t		fid1;		/* HDF5 File IDs		*/
    hid_t		dset1,	/* Dataset ID			*/
                dset2;      /* Dereferenced dataset ID */
    hid_t		sid1,       /* Dataspace ID	#1		*/
                sid2;       /* Dataspace ID	#2		*/
    hsize_t		dims1[] = {SPACE1_DIM1},
            	dims2[] = {SPACE2_DIM1, SPACE2_DIM2};
    hssize_t	start[SPACE2_RANK];     /* Starting location of hyperslab */
    hsize_t		stride[SPACE2_RANK];    /* Stride of hyperslab */
    hsize_t		count[SPACE2_RANK];     /* Element count of hyperslab */
    hsize_t		block[SPACE2_RANK];     /* Block size of hyperslab */
    hssize_t	coord1[POINT1_NPOINTS][SPACE2_RANK]; 
                                    /* Coordinates for point selection */
    hdset_reg_ref_t      *wbuf;      /* buffer to write to disk */
    int     *dwbuf;      /* Buffer for writing numeric data to disk */
    int        i;          /* counting variables */
    herr_t		ret;		/* Generic return value		*/


    /* Allocate write & read buffers */
    wbuf=calloc(sizeof(hdset_reg_ref_t), SPACE1_DIM1);
    dwbuf=malloc(sizeof(int)*SPACE2_DIM1*SPACE2_DIM2);

    /* Create file */
    fid1 = H5Fcreate(FILE2, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

    /* Create dataspace for datasets */
    sid2 = H5Screate_simple(SPACE2_RANK, dims2, NULL);

    /* Create a dataset */
    dset2=H5Dcreate(fid1,"Dataset2",H5T_STD_U8LE,sid2,H5P_DEFAULT);

    for(i=0; i < SPACE2_DIM1*SPACE2_DIM2; i++)
        dwbuf[i]=i*3;

    /* Write selection to disk */
    ret=H5Dwrite(dset2,H5T_NATIVE_INT,H5S_ALL,H5S_ALL,H5P_DEFAULT,dwbuf);

    /* Close Dataset */
    ret = H5Dclose(dset2);

    /* Create dataspace for the reference dataset */
    sid1 = H5Screate_simple(SPACE1_RANK, dims1, NULL);

    /* Create a dataset */
    dset1=H5Dcreate(fid1,"Dataset1",H5T_STD_REF_DSETREG,sid1,H5P_DEFAULT);

    /* Create references */

    /* Select 6x6 hyperslab for first reference */
    start[0]=2; start[1]=2;
    stride[0]=1; stride[1]=1;
    count[0]=6; count[1]=6;
    block[0]=1; block[1]=1;
    ret = H5Sselect_hyperslab(sid2,H5S_SELECT_SET,start,stride,count,block);

    /* Store first dataset region */
    ret = H5Rcreate(&wbuf[0],fid1,"/Dataset2",H5R_DATASET_REGION,sid2);

    /* Select sequence of ten points for second reference */
    coord1[0][0]=6; coord1[0][1]=9;
    coord1[1][0]=2; coord1[1][1]=2;
    coord1[2][0]=8; coord1[2][1]=4;
    coord1[3][0]=1; coord1[3][1]=6;
    coord1[4][0]=2; coord1[4][1]=8;
    coord1[5][0]=3; coord1[5][1]=2;
    coord1[6][0]=0; coord1[6][1]=4;
    coord1[7][0]=9; coord1[7][1]=0;
    coord1[8][0]=7; coord1[8][1]=1;
    coord1[9][0]=3; coord1[9][1]=3;
    ret = H5Sselect_elements(sid2,H5S_SELECT_SET,POINT1_NPOINTS,(const hssize_t **)coord1);

    /* Store second dataset region */
    ret = H5Rcreate(&wbuf[1],fid1,"/Dataset2",H5R_DATASET_REGION,sid2);

    /* Write selection to disk */
    ret=H5Dwrite(dset1,H5T_STD_REF_DSETREG,H5S_ALL,H5S_ALL,H5P_DEFAULT,wbuf);

    /* Close all objects */
    ret = H5Sclose(sid1);
    ret = H5Dclose(dset1);
    ret = H5Sclose(sid2);
    
    /* Close file */
    ret = H5Fclose(fid1);

    free(wbuf);
    free(dwbuf);
    return 0;
}   

Remarks: File Contents: The contents of the file trefer2.h5 created by this program are as follows:
HDF5 "trefer2.h5" {
GROUP "/" {
   DATASET "Dataset1" {
      DATATYPE { H5T_REFERENCE }
      DATASPACE { SIMPLE ( 4 ) / ( 4 ) }
      DATA {
         DATASET 0:744 {(2,2)-(7,7)}, DATASET 0:744 {(6,9), (2,2), (8,4), (1,6),
          (2,8), (3,2), (0,4), (9,0), (7,1), (3,3)}, NULL, NULL
      }
   }
   DATASET "Dataset2" {
      DATATYPE { H5T_STD_U8LE }
      DATASPACE { SIMPLE ( 10, 10 ) / ( 10, 10 ) }
      DATA {
         0, 3, 6, 9, 12, 15, 18, 21, 24, 27,
         30, 33, 36, 39, 42, 45, 48, 51, 54, 57,
         60, 63, 66, 69, 72, 75, 78, 81, 84, 87,
         90, 93, 96, 99, 102, 105, 108, 111, 114, 117,
         120, 123, 126, 129, 132, 135, 138, 141, 144, 147,
         150, 153, 156, 159, 162, 165, 168, 171, 174, 177,
         180, 183, 186, 189, 192, 195, 198, 201, 204, 207,
         210, 213, 216, 219, 222, 225, 228, 231, 234, 237,
         240, 243, 246, 249, 252, 255, 255, 255, 255, 255,
         255, 255, 255, 255, 255, 255, 255, 255, 255, 255
      }
   }
}
}
Notice how raw data of the dataset with the dataset regions is displayed. Each element of the raw data consists of a reference to the dataset (DATASET number1:number2) and its selected region. If the selection is a hyperslab, the corner coordinates of the hyperslab are displayed. For the point selection, the coordinates of each point are displayed. Since only two selections were stored, the third and fourth elements of the dataset Dataset1 are set to NULL. This was done by the buffer inizialization in the program.
Reading references to dataset regions
The following steps are involved in reading references to dataset regions and referenced dataset regions (selections).
  1. Open and read the dataset containing references to the dataset regions. The datatype H5T_STD_REF_DSETREG must be used during read operation.
  2. Use H5Rdereference to obtain the dataset identifier from the read dataset region reference.
                           OR
        
    Use H5Rget_region to obtain the dataspace identifier for the dataset containing the selection from the read dataset region reference.
  3. With the dataspace identifier, the H5S interface functions, H5Sget_select_*, can be used to obtain information about the selection.
  4. Close all objects when they are no longer needed.
Programming Example
Description: The following example [also Example 12] reads a dataset containing dataset region references. It reads data from the dereferenced dataset and displays the number of elements and raw data. Then it reads two selections: a hyperslab selection and a point selection. The program queries a number of points in the hyperslab and the coordinates and displays them. Then it queries a number of selected points and their coordinates and displays the information.
   
#include <stdlib.h>
#include <hdf5.h>

#define FILE2	"trefer2.h5"
#define NPOINTS 10
 
/* 1-D dataset with fixed dimensions */
#define SPACE1_NAME  "Space1"
#define SPACE1_RANK	1
#define SPACE1_DIM1	4

/* 2-D dataset with fixed dimensions */
#define SPACE2_NAME  "Space2"
#define SPACE2_RANK	2
#define SPACE2_DIM1	10
#define SPACE2_DIM2	10

int 
main(void)
{
    hid_t		fid1;		/* HDF5 File IDs		*/
    hid_t		dset1,	/* Dataset ID			*/
                dset2;      /* Dereferenced dataset ID */
    hid_t		sid1,       /* Dataspace ID	#1		*/
                sid2;       /* Dataspace ID	#2		*/
    hsize_t *   coords;             /* Coordinate buffer */
    hsize_t		low[SPACE2_RANK];   /* Selection bounds */
    hsize_t		high[SPACE2_RANK];     /* Selection bounds */
    hdset_reg_ref_t      *rbuf;      /* buffer to to read disk */
    int    *drbuf;      /* Buffer for reading numeric data from disk */
    int        i, j;          /* counting variables */
    herr_t		ret;		/* Generic return value		*/

    /* Output message about test being performed */

    /* Allocate write & read buffers */
    rbuf=malloc(sizeof(hdset_reg_ref_t)*SPACE1_DIM1);
    drbuf=calloc(sizeof(int),SPACE2_DIM1*SPACE2_DIM2);

    /* Open the file */
    fid1 = H5Fopen(FILE2, H5F_ACC_RDWR, H5P_DEFAULT);

    /* Open the dataset */
    dset1=H5Dopen(fid1,"/Dataset1");

    /* Read selection from disk */
    ret=H5Dread(dset1,H5T_STD_REF_DSETREG,H5S_ALL,H5S_ALL,H5P_DEFAULT,rbuf);

    /* Try to open objects */
    dset2 = H5Rdereference(dset1,H5R_DATASET_REGION,&rbuf[0]);

    /* Check information in referenced dataset */
    sid1 = H5Dget_space(dset2);

    ret=H5Sget_simple_extent_npoints(sid1);
    printf(" Number of elements in the dataset is : %d\n",ret);

    /* Read from disk */
    ret=H5Dread(dset2,H5T_NATIVE_INT,H5S_ALL,H5S_ALL,H5P_DEFAULT,drbuf);

    for(i=0; i < SPACE2_DIM1; i++) {
        for (j=0; j < SPACE2_DIM2; j++) printf (" %d ", drbuf[i*SPACE2_DIM2+j]);
        printf("\n"); }

    /* Get the hyperslab selection */
    sid2=H5Rget_region(dset1,H5R_DATASET_REGION,&rbuf[0]);

    /* Verify correct hyperslab selected */
    ret = H5Sget_select_npoints(sid2);
    printf(" Number of elements in the hyperslab is : %d \n", ret);
    ret = H5Sget_select_hyper_nblocks(sid2);
    coords=malloc(ret*SPACE2_RANK*sizeof(hsize_t)*2); /* allocate space for the hyperslab blocks */
    ret = H5Sget_select_hyper_blocklist(sid2,0,ret,coords);
    printf(" Hyperslab coordinates are : \n");
    printf (" ( %lu , %lu ) ( %lu , %lu ) \n", \
(unsigned long)coords[0],(unsigned long)coords[1],(unsigned long)coords[2],(unsigned long)coords[3]); 
    free(coords);
    ret = H5Sget_select_bounds(sid2,low,high);

    /* Close region space */
    ret = H5Sclose(sid2);

    /* Get the element selection */
    sid2=H5Rget_region(dset1,H5R_DATASET_REGION,&rbuf[1]);

    /* Verify correct elements selected */
    ret = H5Sget_select_elem_npoints(sid2);
    printf(" Number of selected elements is : %d\n", ret);

    /* Allocate space for the element points */
    coords= malloc(ret*SPACE2_RANK*sizeof(hsize_t)); 
    ret = H5Sget_select_elem_pointlist(sid2,0,ret,coords);
    printf(" Coordinates of selected elements are : \n");
    for (i=0; i < 2*NPOINTS; i=i+2) 
         printf(" ( %lu , %lu ) \n", (unsigned long)coords[i],(unsigned long)coords[i+1]); 
          
    free(coords);
    ret = H5Sget_select_bounds(sid2,low,high);

    /* Close region space */
    ret = H5Sclose(sid2);

    /* Close first space */
    ret = H5Sclose(sid1);

    /* Close dereferenced Dataset */
    ret = H5Dclose(dset2);

    /* Close Dataset */
    ret = H5Dclose(dset1);

    /* Close file */
    ret = H5Fclose(fid1);

    /* Free memory buffers */
    free(rbuf);
    free(drbuf);
    return 0;
}   

The output of this program is :


 Number of elements in the dataset is : 100
 0  3  6  9  12  15  18  21  24  27 
 30  33  36  39  42  45  48  51  54  57 
 60  63  66  69  72  75  78  81  84  87 
 90  93  96  99  102  105  108  111  114  117 
 120  123  126  129  132  135  138  141  144  147 
 150  153  156  159  162  165  168  171  174  177 
 180  183  186  189  192  195  198  201  204  207 
 210  213  216  219  222  225  228  231  234  237 
 240  243  246  249  252  255  255  255  255  255 
 255  255  255  255  255  255  255  255  255  255 
 Number of elements in the hyperslab is : 36 
 Hyperslab coordinates are : 
 ( 2 , 2 ) ( 7 , 7 ) 
 Number of selected elements is : 10
 Coordinates of selected elements are : 
 ( 6 , 9 ) 
 ( 2 , 2 ) 
 ( 8 , 4 ) 
 ( 1 , 6 ) 
 ( 2 , 8 ) 
 ( 3 , 2 ) 
 ( 0 , 4 ) 
 ( 9 , 0 ) 
 ( 7 , 1 ) 
 ( 3 , 3 ) 
 
Remarks:

(Return to TOC)


4. Example Codes

Example 1: How to create a homogeneous multi-dimensional dataset and write it to a file.

This example creates a 2-dimensional HDF 5 dataset of little endian 32-bit integers.


/*  
 *  This example writes data to the HDF5 file.
 *  Data conversion is performed during write operation.  
 */
 
#include 

#define FILE        "SDS.h5"
#define DATASETNAME "IntArray" 
#define NX     5                      /* dataset dimensions */
#define NY     6
#define RANK   2

int
main (void)
{
    hid_t       file, dataset;         /* file and dataset handles */
    hid_t       datatype, dataspace;   /* handles */
    hsize_t     dimsf[2];              /* dataset dimensions */
    herr_t      status;                             
    int         data[NX][NY];          /* data to write */
    int         i, j;

    /* 
     * Data  and output buffer initialization. 
     */
    for (j = 0; j < NX; j++) {
	for (i = 0; i < NY; i++)
	    data[j][i] = i + j;
    }     
    /*
     * 0 1 2 3 4 5 
     * 1 2 3 4 5 6
     * 2 3 4 5 6 7
     * 3 4 5 6 7 8
     * 4 5 6 7 8 9
     */

    /*
     * Create a new file using H5F_ACC_TRUNC access,
     * default file creation properties, and default file
     * access properties.
     */
    file = H5Fcreate(FILE, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

    /*
     * Describe the size of the array and create the data space for fixed
     * size dataset. 
     */
    dimsf[0] = NX;
    dimsf[1] = NY;
    dataspace = H5Screate_simple(RANK, dimsf, NULL); 

    /* 
     * Define datatype for the data in the file.
     * We will store little endian INT numbers.
     */
    datatype = H5Tcopy(H5T_NATIVE_INT);
    status = H5Tset_order(datatype, H5T_ORDER_LE);

    /*
     * Create a new dataset within the file using defined dataspace and
     * datatype and default dataset creation properties.
     */
    dataset = H5Dcreate(file, DATASETNAME, datatype, dataspace,
			H5P_DEFAULT);

    /*
     * Write the data to the dataset using default transfer properties.
     */
    status = H5Dwrite(dataset, H5T_NATIVE_INT, H5S_ALL, H5S_ALL,
		      H5P_DEFAULT, data);

    /*
     * Close/release resources.
     */
    H5Sclose(dataspace);
    H5Tclose(datatype);
    H5Dclose(dataset);
    H5Fclose(file);
 
    return 0;
}     
 

Example 2. How to read a hyperslab from file into memory.

This example reads a hyperslab from a 2-d HDF5 dataset into a 3-d dataset in memory.


/*  
 *   This example reads hyperslab from the SDS.h5 file 
 *   created by h5_write.c program into two-dimensional
 *   plane of the three-dimensional array. 
 *   Information about dataset in the SDS.h5 file is obtained. 
 */
 
#include "hdf5.h"

#define FILE        "SDS.h5"
#define DATASETNAME "IntArray" 
#define NX_SUB  3           /* hyperslab dimensions */ 
#define NY_SUB  4 
#define NX 7           /* output buffer dimensions */ 
#define NY 7 
#define NZ  3 
#define RANK         2
#define RANK_OUT     3

int
main (void)
{
    hid_t       file, dataset;         /* handles */
    hid_t       datatype, dataspace;   
    hid_t       memspace; 
    H5T_class_t class;                 /* datatype class */
    H5T_order_t order;                 /* data order */
    size_t      size;                  /*
				        * size of the data element	       
				        * stored in file
				        */
    hsize_t     dimsm[3];              /* memory space dimensions */
    hsize_t     dims_out[2];           /* dataset dimensions */      
    herr_t      status;                             

    int         data_out[NX][NY][NZ ]; /* output buffer */
   
    hsize_t      count[2];              /* size of the hyperslab in the file */
    hssize_t     offset[2];             /* hyperslab offset in the file */
    hsize_t      count_out[3];          /* size of the hyperslab in memory */
    hssize_t     offset_out[3];         /* hyperslab offset in memory */
    int          i, j, k, status_n, rank;

    for (j = 0; j < NX; j++) {
	for (i = 0; i < NY; i++) {
	    for (k = 0; k < NZ ; k++)
		data_out[j][i][k] = 0;
	}
    } 
 
    /*
     * Open the file and the dataset.
     */
    file = H5Fopen(FILE, H5F_ACC_RDONLY, H5P_DEFAULT);
    dataset = H5Dopen(file, DATASETNAME);

    /*
     * Get datatype and dataspace handles and then query
     * dataset class, order, size, rank and dimensions.
     */
    datatype  = H5Dget_type(dataset);     /* datatype handle */ 
    class     = H5Tget_class(datatype);
    if (class == H5T_INTEGER) printf("Data set has INTEGER type \n");
    order     = H5Tget_order(datatype);
    if (order == H5T_ORDER_LE) printf("Little endian order \n");

    size  = H5Tget_size(datatype);
    printf(" Data size is %d \n", size);

    dataspace = H5Dget_space(dataset);    /* dataspace handle */
    rank      = H5Sget_simple_extent_ndims(dataspace);
    status_n  = H5Sget_simple_extent_dims(dataspace, dims_out, NULL);
    printf("rank %d, dimensions %lu x %lu \n", rank,
	   (unsigned long)(dims_out[0]), (unsigned long)(dims_out[1]));

    /* 
     * Define hyperslab in the dataset. 
     */
    offset[0] = 1;
    offset[1] = 2;
    count[0]  = NX_SUB;
    count[1]  = NY_SUB;
    status = H5Sselect_hyperslab(dataspace, H5S_SELECT_SET, offset, NULL, 
				 count, NULL);

    /*
     * Define the memory dataspace.
     */
    dimsm[0] = NX;
    dimsm[1] = NY;
    dimsm[2] = NZ ;
    memspace = H5Screate_simple(RANK_OUT,dimsm,NULL);   

    /* 
     * Define memory hyperslab. 
     */
    offset_out[0] = 3;
    offset_out[1] = 0;
    offset_out[2] = 0;
    count_out[0]  = NX_SUB;
    count_out[1]  = NY_SUB;
    count_out[2]  = 1;
    status = H5Sselect_hyperslab(memspace, H5S_SELECT_SET, offset_out, NULL, 
				 count_out, NULL);

    /*
     * Read data from hyperslab in the file into the hyperslab in 
     * memory and display.
     */
    status = H5Dread(dataset, H5T_NATIVE_INT, memspace, dataspace,
		     H5P_DEFAULT, data_out);
    for (j = 0; j < NX; j++) {
	for (i = 0; i < NY; i++) printf("%d ", data_out[j][i][0]);
	printf("\n");
    }
    /*
     * 0 0 0 0 0 0 0
     * 0 0 0 0 0 0 0
     * 0 0 0 0 0 0 0
     * 3 4 5 6 0 0 0  
     * 4 5 6 7 0 0 0
     * 5 6 7 8 0 0 0
     * 0 0 0 0 0 0 0
     */

    /*
     * Close/release resources.
     */
    H5Tclose(datatype);
    H5Dclose(dataset);
    H5Sclose(dataspace);
    H5Sclose(memspace);
    H5Fclose(file);

    return 0;
}     

Example 3. Writing selected data from memory to a file.

This example shows how to use the selection capabilities of HDF5 to write selected data to a file. It includes the examples discussed in the text.


/* 
 *  This program shows how the H5Sselect_hyperslab and H5Sselect_elements
 *  functions are used to write selected data from memory to the file.
 *  Program takes 48 elements from the linear buffer and writes them into
 *  the matrix using 3x2 blocks, (4,3) stride and (2,4) count. 
 *  Then four elements  of the matrix are overwritten with the new values and 
 *  file is closed. Program reopens the file and reads and displays the result.
 */ 
 
#include 

#define FILE "Select.h5"

#define MSPACE1_RANK     1          /* Rank of the first dataset in memory */
#define MSPACE1_DIM      50         /* Dataset size in memory */ 

#define MSPACE2_RANK     1          /* Rank of the second dataset in memory */ 
#define MSPACE2_DIM      4          /* Dataset size in memory */ 

#define FSPACE_RANK      2          /* Dataset rank as it is stored in the file */
#define FSPACE_DIM1      8          /* Dimension sizes of the dataset as it is
                                       stored in the file */
#define FSPACE_DIM2      12 

                                    /* We will read dataset back from the file
                                       to the dataset in memory with these
                                       dataspace parameters. */  
#define MSPACE_RANK      2
#define MSPACE_DIM1      8 
#define MSPACE_DIM2      12 

#define NPOINTS          4          /* Number of points that will be selected 
                                       and overwritten */ 
int main (void)
{

   hid_t   file, dataset;           /* File and dataset identifiers */
   hid_t   mid1, mid2, fid;         /* Dataspace identifiers */
   hsize_t dim1[] = {MSPACE1_DIM};  /* Dimension size of the first dataset 
                                       (in memory) */ 
   hsize_t dim2[] = {MSPACE2_DIM};  /* Dimension size of the second dataset
                                       (in memory */ 
   hsize_t fdim[] = {FSPACE_DIM1, FSPACE_DIM2}; 
                                    /* Dimension sizes of the dataset (on disk) */

   hssize_t start[2]; /* Start of hyperslab */
   hsize_t stride[2]; /* Stride of hyperslab */
   hsize_t count[2];  /* Block count */
   hsize_t block[2];  /* Block sizes */

   hssize_t coord[NPOINTS][FSPACE_RANK]; /* Array to store selected points 
                                            from the file dataspace */ 
   herr_t  ret;
   uint    i,j;
   int     matrix[MSPACE_DIM1][MSPACE_DIM2];
   int     vector[MSPACE1_DIM];
   int     values[] = {53, 59, 61, 67};  /* New values to be written */

   /*
    * Buffers' initialization.
    */
   vector[0] = vector[MSPACE1_DIM - 1] = -1;
   for (i = 1; i < MSPACE1_DIM - 1; i++) vector[i] = i;

   for (i = 0; i < MSPACE_DIM1; i++) {
       for (j = 0; j < MSPACE_DIM2; j++)
       matrix[i][j] = 0;
    }

    /*
     * Create a file.
     */
    file = H5Fcreate(FILE, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

    /* 
     * Create dataspace for the dataset in the file.
     */
    fid = H5Screate_simple(FSPACE_RANK, fdim, NULL);

    /*
     * Create dataset and write it into the file.
     */
    dataset = H5Dcreate(file, "Matrix in file", H5T_NATIVE_INT, fid, H5P_DEFAULT);
    ret = H5Dwrite(dataset, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, matrix);

    /*
     * Select hyperslab for the dataset in the file, using 3x2 blocks, 
     * (4,3) stride and (2,4) count starting at the position (0,1).
     */
    start[0]  = 0; start[1]  = 1;
    stride[0] = 4; stride[1] = 3;
    count[0]  = 2; count[1]  = 4;    
    block[0]  = 3; block[1]  = 2;
    ret = H5Sselect_hyperslab(fid, H5S_SELECT_SET, start, stride, count, block);

    /*
     * Create dataspace for the first dataset.
     */
    mid1 = H5Screate_simple(MSPACE1_RANK, dim1, NULL);

    /*
     * Select hyperslab. 
     * We will use 48 elements of the vector buffer starting at the second element.
     * Selected elements are 1 2 3 . . . 48
     */
    start[0]  = 1;
    stride[0] = 1;
    count[0]  = 48;
    block[0]  = 1;
    ret = H5Sselect_hyperslab(mid1, H5S_SELECT_SET, start, stride, count, block);
 
    /*
     * Write selection from the vector buffer to the dataset in the file.
     *
     * File dataset should look like this:       
     *                    0  1  2  0  3  4  0  5  6  0  7  8 
     *                    0  9 10  0 11 12  0 13 14  0 15 16
     *                    0 17 18  0 19 20  0 21 22  0 23 24
     *                    0  0  0  0  0  0  0  0  0  0  0  0
     *                    0 25 26  0 27 28  0 29 30  0 31 32
     *                    0 33 34  0 35 36  0 37 38  0 39 40
     *                    0 41 42  0 43 44  0 45 46  0 47 48
     *                    0  0  0  0  0  0  0  0  0  0  0  0
     */
     ret = H5Dwrite(dataset, H5T_NATIVE_INT, mid1, fid, H5P_DEFAULT, vector);

    /*
     * Reset the selection for the file dataspace fid.
     */
    ret = H5Sselect_none(fid);

    /*
     * Create dataspace for the second dataset.
     */
    mid2 = H5Screate_simple(MSPACE2_RANK, dim2, NULL);

    /*
     * Select sequence of NPOINTS points in the file dataspace.
     */
    coord[0][0] = 0; coord[0][1] = 0;
    coord[1][0] = 3; coord[1][1] = 3;
    coord[2][0] = 3; coord[2][1] = 5;
    coord[3][0] = 5; coord[3][1] = 6;

    ret = H5Sselect_elements(fid, H5S_SELECT_SET, NPOINTS, 
                             (const hssize_t **)coord);

    /*
     * Write new selection of points to the dataset.
     */
    ret = H5Dwrite(dataset, H5T_NATIVE_INT, mid2, fid, H5P_DEFAULT, values);   

    /*
     * File dataset should look like this:     
     *                   53  1  2  0  3  4  0  5  6  0  7  8 
     *                    0  9 10  0 11 12  0 13 14  0 15 16
     *                    0 17 18  0 19 20  0 21 22  0 23 24
     *                    0  0  0 59  0 61  0  0  0  0  0  0
     *                    0 25 26  0 27 28  0 29 30  0 31 32
     *                    0 33 34  0 35 36 67 37 38  0 39 40
     *                    0 41 42  0 43 44  0 45 46  0 47 48
     *                    0  0  0  0  0  0  0  0  0  0  0  0
     *                                        
     */
   
    /*
     * Close memory file and memory dataspaces.
     */
    ret = H5Sclose(mid1); 
    ret = H5Sclose(mid2); 
    ret = H5Sclose(fid); 
 
    /*
     * Close dataset.
     */
    ret = H5Dclose(dataset);

    /*
     * Close the file.
     */
    ret = H5Fclose(file);

    /*
     * Open the file.
     */
    file = H5Fopen(FILE, H5F_ACC_RDONLY, H5P_DEFAULT);

    /*
     * Open the dataset.
     */
    dataset = dataset = H5Dopen(file,"Matrix in file");

    /*
     * Read data back to the buffer matrix.
     */
    ret = H5Dread(dataset, H5T_NATIVE_INT, H5S_ALL, H5S_ALL,
                  H5P_DEFAULT, matrix);

    /*
     * Display the result.
     */
    for (i=0; i < MSPACE_DIM1; i++) {
        for(j=0; j < MSPACE_DIM2; j++) printf("%3d  ", matrix[i][j]);
        printf("\n");
    }

    return 0;
}

Example 4. Working with compound datatypes.

This example shows how to create a compound datatype, write an array which has the compound datatype to the file, and read back subsets of fields.


/*
 * This example shows how to create a compound datatype,
 * write an array which has the compound datatype to the file,
 * and read back fields' subsets.
 */

#include "hdf5.h"

#define FILE          "SDScompound.h5"
#define DATASETNAME   "ArrayOfStructures"
#define LENGTH        10
#define RANK          1

int
main(void)
{

    /* First structure  and dataset*/
    typedef struct s1_t {
	int    a;
	float  b;
	double c; 
    } s1_t;
    s1_t       s1[LENGTH];
    hid_t      s1_tid;     /* File datatype identifier */

    /* Second structure (subset of s1_t)  and dataset*/
    typedef struct s2_t {
	double c;
	int    a;
    } s2_t;
    s2_t       s2[LENGTH];
    hid_t      s2_tid;    /* Memory datatype handle */

    /* Third "structure" ( will be used to read float field of s1) */
    hid_t      s3_tid;   /* Memory datatype handle */
    float      s3[LENGTH];

    int        i;
    hid_t      file, dataset, space; /* Handles */
    herr_t     status;
    hsize_t    dim[] = {LENGTH};   /* Dataspace dimensions */


    /*
     * Initialize the data
     */
    for (i = 0; i< LENGTH; i++) {
        s1[i].a = i;
        s1[i].b = i*i;
        s1[i].c = 1./(i+1);
    }

    /*
     * Create the data space.
     */
    space = H5Screate_simple(RANK, dim, NULL);

    /*
     * Create the file.
     */
    file = H5Fcreate(FILE, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

    /*
     * Create the memory datatype. 
     */
    s1_tid = H5Tcreate (H5T_COMPOUND, sizeof(s1_t));
    H5Tinsert(s1_tid, "a_name", HOFFSET(s1_t, a), H5T_NATIVE_INT);
    H5Tinsert(s1_tid, "c_name", HOFFSET(s1_t, c), H5T_NATIVE_DOUBLE);
    H5Tinsert(s1_tid, "b_name", HOFFSET(s1_t, b), H5T_NATIVE_FLOAT);

    /* 
     * Create the dataset.
     */
    dataset = H5Dcreate(file, DATASETNAME, s1_tid, space, H5P_DEFAULT);

    /*
     * Wtite data to the dataset; 
     */
    status = H5Dwrite(dataset, s1_tid, H5S_ALL, H5S_ALL, H5P_DEFAULT, s1);

    /*
     * Release resources
     */
    H5Tclose(s1_tid);
    H5Sclose(space);
    H5Dclose(dataset);
    H5Fclose(file);
 
    /*
     * Open the file and the dataset.
     */
    file = H5Fopen(FILE, H5F_ACC_RDONLY, H5P_DEFAULT);
 
    dataset = H5Dopen(file, DATASETNAME);

    /* 
     * Create a datatype for s2
     */
    s2_tid = H5Tcreate(H5T_COMPOUND, sizeof(s2_t));

    H5Tinsert(s2_tid, "c_name", HOFFSET(s2_t, c), H5T_NATIVE_DOUBLE);
    H5Tinsert(s2_tid, "a_name", HOFFSET(s2_t, a), H5T_NATIVE_INT);

    /*
     * Read two fields c and a from s1 dataset. Fields in the file
     * are found by their names "c_name" and "a_name".
     */
    status = H5Dread(dataset, s2_tid, H5S_ALL, H5S_ALL, H5P_DEFAULT, s2);

    /*
     * Display the fields
     */
    printf("\n");
    printf("Field c : \n");
    for( i = 0; i < LENGTH; i++) printf("%.4f ", s2[i].c);
    printf("\n");

    printf("\n");
    printf("Field a : \n");
    for( i = 0; i < LENGTH; i++) printf("%d ", s2[i].a);
    printf("\n");

    /* 
     * Create a datatype for s3.
     */
    s3_tid = H5Tcreate(H5T_COMPOUND, sizeof(float));

    status = H5Tinsert(s3_tid, "b_name", 0, H5T_NATIVE_FLOAT);

    /*
     * Read field b from s1 dataset. Field in the file is found by its name.
     */
    status = H5Dread(dataset, s3_tid, H5S_ALL, H5S_ALL, H5P_DEFAULT, s3);

    /*
     * Display the field
     */
    printf("\n");
    printf("Field b : \n");
    for( i = 0; i < LENGTH; i++) printf("%.4f ", s3[i]);
    printf("\n");

    /*
     * Release resources
     */
    H5Tclose(s2_tid);
    H5Tclose(s3_tid);
    H5Dclose(dataset);
    H5Fclose(file);

    return 0;
}

Example 5. Creating and writing an extendible dataset.

This example shows how to create a 3x3 extendible dataset, to extend the dataset to 10x3, then to extend it again to 10x5.


/*  
 *   This example shows how to work with extendible dataset.
 *   In the current version of the library dataset MUST be
 *   chunked.
 *   
 */
 
#include "hdf5.h"

#define FILE        "SDSextendible.h5"
#define DATASETNAME "ExtendibleArray" 
#define RANK         2
#define NX     10
#define NY     5 

int
main (void)
{
    hid_t       file;                          /* handles */
    hid_t       dataspace, dataset;  
    hid_t       filespace;                   
    hid_t       cparms;                     
    hsize_t      dims[2]  = { 3, 3};            /*
						 * dataset dimensions				
						 * at the creation time
						 */
    hsize_t      dims1[2] = { 3, 3};            /* data1 dimensions */ 
    hsize_t      dims2[2] = { 7, 1};            /* data2 dimensions */  
    hsize_t      dims3[2] = { 2, 2};            /* data3 dimensions */ 

    hsize_t      maxdims[2] = {H5S_UNLIMITED, H5S_UNLIMITED};
    hsize_t      chunk_dims[2] ={2, 5};
    hsize_t      size[2];
    hssize_t     offset[2];

    herr_t      status;                             

    int         data1[3][3] = { {1, 1, 1},       /* data to write */
				{1, 1, 1},
				{1, 1, 1} };      

    int         data2[7]    = { 2, 2, 2, 2, 2, 2, 2};

    int         data3[2][2] = { {3, 3},
				{3, 3} };

    /*
     * Create the data space with unlimited dimensions. 
     */
    dataspace = H5Screate_simple(RANK, dims, maxdims); 

    /*
     * Create a new file. If file exists its contents will be overwritten.
     */
    file = H5Fcreate(FILE, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

    /* 
     * Modify dataset creation properties, i.e. enable chunking.
     */
    cparms = H5Pcreate (H5P_DATASET_CREATE);
    status = H5Pset_chunk( cparms, RANK, chunk_dims);

    /*
     * Create a new dataset within the file using cparms
     * creation properties.
     */
    dataset = H5Dcreate(file, DATASETNAME, H5T_NATIVE_INT, dataspace,
			cparms);

    /*
     * Extend the dataset. This call assures that dataset is at least 3 x 3.
     */
    size[0]   = 3; 
    size[1]   = 3; 
    status = H5Dextend (dataset, size);

    /*
     * Select a hyperslab.
     */
    filespace = H5Dget_space (dataset);
    offset[0] = 0;
    offset[1] = 0;
    status = H5Sselect_hyperslab(filespace, H5S_SELECT_SET, offset, NULL,
				 dims1, NULL);  

    /*
     * Write the data to the hyperslab.
     */
    status = H5Dwrite(dataset, H5T_NATIVE_INT, dataspace, filespace,
		      H5P_DEFAULT, data1);

    /*
     * Extend the dataset. Dataset becomes 10 x 3.
     */
    dims[0]   = dims1[0] + dims2[0];
    size[0]   = dims[0];  
    size[1]   = dims[1]; 
    status = H5Dextend (dataset, size);

    /*
     * Select a hyperslab.
     */
    filespace = H5Dget_space (dataset);
    offset[0] = 3;
    offset[1] = 0;
    status = H5Sselect_hyperslab(filespace, H5S_SELECT_SET, offset, NULL,
				 dims2, NULL);  

    /*
     * Define memory space
     */
    dataspace = H5Screate_simple(RANK, dims2, NULL); 

    /*
     * Write the data to the hyperslab.
     */
    status = H5Dwrite(dataset, H5T_NATIVE_INT, dataspace, filespace,
		      H5P_DEFAULT, data2);

    /*
     * Extend the dataset. Dataset becomes 10 x 5.
     */
    dims[1]   = dims1[1] + dims3[1];
    size[0]   = dims[0];  
    size[1]   = dims[1]; 
    status = H5Dextend (dataset, size);

    /*
     * Select a hyperslab
     */
    filespace = H5Dget_space (dataset);
    offset[0] = 0;
    offset[1] = 3;
    status = H5Sselect_hyperslab(filespace, H5S_SELECT_SET, offset, NULL, 
				 dims3, NULL);  

    /*
     * Define memory space.
     */
    dataspace = H5Screate_simple(RANK, dims3, NULL); 

    /*
     * Write the data to the hyperslab.
     */
    status = H5Dwrite(dataset, H5T_NATIVE_INT, dataspace, filespace,
		      H5P_DEFAULT, data3);

    /*
     * Resulting dataset
     * 
     *	 3 3 3 2 2
     *	 3 3 3 2 2
     *	 3 3 3 0 0
     *	 2 0 0 0 0
     *	 2 0 0 0 0
     *	 2 0 0 0 0
     *	 2 0 0 0 0
     *	 2 0 0 0 0
     *	 2 0 0 0 0
     *	 2 0 0 0 0
     */
    /*
     * Close/release resources.
     */
    H5Dclose(dataset);
    H5Sclose(dataspace);
    H5Sclose(filespace);
    H5Fclose(file);

    return 0;
}     

Example 6. Reading data.

This example shows how to read information the chunked dataset written by Example 5.


/*  
 *   This example shows how to read data from a chunked dataset.
 *   We will read from the file created by h5_extend_write.c 
 */
 
#include "hdf5.h"

#define FILE        "SDSextendible.h5"
#define DATASETNAME "ExtendibleArray" 
#define RANK         2
#define RANKC        1
#define NX           10
#define NY           5 

int
main (void)
{
    hid_t       file;                        /* handles */
    hid_t       dataset;  
    hid_t       filespace;                   
    hid_t       memspace;                  
    hid_t       cparms;                   
    hsize_t     dims[2];                     /* dataset and chunk dimensions*/ 
    hsize_t     chunk_dims[2];
    hsize_t     col_dims[1];
    hsize_t     count[2];
    hssize_t    offset[2];

    herr_t      status, status_n;                             

    int         data_out[NX][NY];  /* buffer for dataset to be read */
    int         chunk_out[2][5];   /* buffer for chunk to be read */
    int         column[10];        /* buffer for column to be read */
    int         rank, rank_chunk;
    hsize_t	i, j;
    

 
    /*
     * Open the file and the dataset.
     */
    file = H5Fopen(FILE, H5F_ACC_RDONLY, H5P_DEFAULT);
    dataset = H5Dopen(file, DATASETNAME);
 
    /*
     * Get dataset rank and dimension.
     */

    filespace = H5Dget_space(dataset);    /* Get filespace handle first. */
    rank      = H5Sget_simple_extent_ndims(filespace);
    status_n  = H5Sget_simple_extent_dims(filespace, dims, NULL);
    printf("dataset rank %d, dimensions %lu x %lu\n",
	   rank, (unsigned long)(dims[0]), (unsigned long)(dims[1]));

    /*
     * Get creation properties list.
     */
    cparms = H5Dget_create_plist(dataset); /* Get properties handle first. */

    /* 
     * Check if dataset is chunked.
     */
    if (H5D_CHUNKED == H5Pget_layout(cparms))  {

	/*
	 * Get chunking information: rank and dimensions
	 */
	rank_chunk = H5Pget_chunk(cparms, 2, chunk_dims);
	printf("chunk rank %d, dimensions %lu x %lu\n", rank_chunk,
	       (unsigned long)(chunk_dims[0]), (unsigned long)(chunk_dims[1]));
    }
 
    /*
     * Define the memory space to read dataset.
     */
    memspace = H5Screate_simple(RANK,dims,NULL);
 
    /*
     * Read dataset back and display.
     */
    status = H5Dread(dataset, H5T_NATIVE_INT, memspace, filespace,
		     H5P_DEFAULT, data_out);
    printf("\n");
    printf("Dataset: \n");
    for (j = 0; j < dims[0]; j++) {
	for (i = 0; i < dims[1]; i++) printf("%d ", data_out[j][i]);
	printf("\n");
    }     

    /*
     *	    dataset rank 2, dimensions 10 x 5 
     *	    chunk rank 2, dimensions 2 x 5 

     *	    Dataset:
     *	    1 1 1 3 3 
     *	    1 1 1 3 3 
     *	    1 1 1 0 0 
     *	    2 0 0 0 0 
     *	    2 0 0 0 0 
     *	    2 0 0 0 0 
     *	    2 0 0 0 0 
     *	    2 0 0 0 0 
     *	    2 0 0 0 0 
     *	    2 0 0 0 0 
     */

    /*
     * Read the third column from the dataset.
     * First define memory dataspace, then define hyperslab
     * and read it into column array.
     */
    col_dims[0] = 10;
    memspace =  H5Screate_simple(RANKC, col_dims, NULL);

    /*
     * Define the column (hyperslab) to read.
     */
    offset[0] = 0;
    offset[1] = 2;
    count[0]  = 10;
    count[1]  = 1;
    status = H5Sselect_hyperslab(filespace, H5S_SELECT_SET, offset, NULL,
				 count, NULL);
    status = H5Dread(dataset, H5T_NATIVE_INT, memspace, filespace,
		     H5P_DEFAULT, column);
    printf("\n");
    printf("Third column: \n");
    for (i = 0; i < 10; i++) {
	printf("%d \n", column[i]);
    }

    /*
     *	    Third column: 
     *	    1 
     *	    1 
     *	    1 
     *	    0 
     *	    0 
     *	    0 
     *	    0 
     *	    0 
     *	    0 
     *	    0 
     */

    /*
     * Define the memory space to read a chunk.
     */
    memspace = H5Screate_simple(rank_chunk,chunk_dims,NULL);

    /*
     * Define chunk in the file (hyperslab) to read.
     */
    offset[0] = 2;
    offset[1] = 0;
    count[0]  = chunk_dims[0];
    count[1]  = chunk_dims[1];
    status = H5Sselect_hyperslab(filespace, H5S_SELECT_SET, offset, NULL, 
				 count, NULL);

    /*
     * Read chunk back and display.
     */
    status = H5Dread(dataset, H5T_NATIVE_INT, memspace, filespace,
		     H5P_DEFAULT, chunk_out);
    printf("\n");
    printf("Chunk: \n");
    for (j = 0; j < chunk_dims[0]; j++) {
	for (i = 0; i < chunk_dims[1]; i++) printf("%d ", chunk_out[j][i]);
	printf("\n");
    }     
    /*
     *	 Chunk: 
     *	 1 1 1 0 0 
     *	 2 0 0 0 0 
     */

    /*
     * Close/release resources.
     */
    H5Pclose(cparms);
    H5Dclose(dataset);
    H5Sclose(filespace);
    H5Sclose(memspace);
    H5Fclose(file);

    return 0;

Example 7. Creating groups.

This example shows how to create and access a group in an HDF5 file and to place a dataset within this group. It also illustrates the usage of the H5Giterate, H5Glink, and H5Gunlink functions.


/*
 * This example creates a group in the file and dataset in the group. 
 * Hard link to the group object is created and the dataset is accessed
 * under different names. 
 * Iterator function is used to find the object names in the root group.
 */ 


#include "hdf5.h"


#define FILE    "group.h5"
#define RANK    2

 
herr_t file_info(hid_t loc_id, const char *name, void *opdata);
                                     /* Operator function */
int
main(void)
{

    hid_t    file;
    hid_t    grp;
    hid_t    dataset, dataspace;
    hid_t    plist; 

    herr_t   status;
    hsize_t  dims[2];
    hsize_t  cdims[2];
 
    int      idx;

    /*
     * Create a file.
     */
    file = H5Fcreate(FILE, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

    /*
     * Create a group in the file. 
     */
    grp = H5Gcreate(file, "/Data", 0);

    /*
     * Create dataset "Compressed Data" in the group using absolute
     * name. Dataset creation property list is modified to use 
     * GZIP compression with the compression effort set to 6. 
     * Note that compression can be used only when dataset is chunked. 
     */
    dims[0] = 1000;
    dims[1] = 20;
    cdims[0] = 20;
    cdims[1] = 20;
    dataspace = H5Screate_simple(RANK, dims, NULL);
    plist     = H5Pcreate(H5P_DATASET_CREATE);
                H5Pset_chunk(plist, 2, cdims);
                H5Pset_deflate( plist, 6); 
    dataset = H5Dcreate(file, "/Data/Compressed_Data", H5T_NATIVE_INT, 
                        dataspace, plist); 
 
    /* 
     * Close the dataset and the file.
     */
    H5Sclose(dataspace);
    H5Dclose(dataset);
    H5Fclose(file);

    /*
     * Now reopen the file and group in the file. 
     */
    file = H5Fopen(FILE, H5F_ACC_RDWR, H5P_DEFAULT);
    grp  = H5Gopen(file, "Data");

    /* 
     * Access "Compressed_Data" dataset in the group. 
     */
    dataset = H5Dopen(grp, "Compressed_Data");
    if( dataset < 0) printf(" Dataset is not found. \n");
    printf("\"/Data/Compressed_Data\" dataset is open \n");

    /*
     * Close the dataset.
     */
    status = H5Dclose(dataset);

    /*
     * Create hard link to the Data group.
     */
    status = H5Glink(file, H5G_LINK_HARD, "Data", "Data_new");

    /* 
     * We can access "Compressed_Data" dataset using created
     * hard link "Data_new". 
     */
    dataset = H5Dopen(file, "/Data_new/Compressed_Data");
    if( dataset < 0) printf(" Dataset is not found. \n");
    printf("\"/Data_new/Compressed_Data\" dataset is open \n");

    /*
     * Close the dataset.
     */
    status = H5Dclose(dataset);

    /* 
     * Use iterator to see the names of the objects in the file
     * root directory.
     */
    idx = H5Giterate(file, "/", NULL, file_info, NULL);

    /*
     * Unlink  name "Data" and use iterator to see the names
     * of the objects in the file root direvtory.
     */
    if (H5Gunlink(file, "Data") < 0)  
      printf(" H5Gunlink failed \n");
    else  
      printf("\"Data\" is unlinked \n");

    idx = H5Giterate(file, "/", NULL, file_info, NULL);
    

    /*
     * Close the file.
     */
     
    status = H5Fclose(file);

    return 0;
}
/*
 * Operator function.
 */
herr_t
file_info(hid_t loc_id, const char *name, void *opdata)
{
    hid_t grp;
    /*
     * Open the group using its name.
     */
    grp = H5Gopen(loc_id, name);
 
    /*
     * Display group name.
     */
    printf("\n");
    printf("Name : ");
    puts(name);
    
    H5Gclose(grp);
    return 0;
 }

Example 8. Writing and reading attributes.

This example shows how to create HDF5 attributes, to attach them to a dataset, and to read through all of the attributes of a dataset.


/* 
 *  This program illustrates the usage of the H5A Interface functions.
 *  It creates and writes a dataset, and then creates and writes array,
 *  scalar, and string attributes of the dataset. 
 *  Program reopens the file, attaches to the scalar attribute using
 *  attribute name and reads and displays its value. Then index of the
 *  third attribute is used to read and display attribute values.
 *  The H5Aiterate function is used to iterate through the dataset attributes,
 *  and display their names. The function is also reads and displays the values 
 *  of the array attribute. 
 */ 
 
#include 
#include 

#define FILE "Attributes.h5"

#define RANK  1   /* Rank and size of the dataset  */ 
#define SIZE  7

#define ARANK  2   /* Rank and dimension sizes of the first dataset attribute */
#define ADIM1  2
#define ADIM2  3 
#define ANAME  "Float attribute"      /* Name of the array attribute */
#define ANAMES "Character attribute" /* Name of the string attribute */

herr_t attr_info(hid_t loc_id, const char *name, void *opdata); 
                                     /* Operator function */

int 
main (void)
{

   hid_t   file, dataset;       /* File and dataset identifiers */
   
   hid_t   fid;                 /* Dataspace identifier */
   hid_t   attr1, attr2, attr3; /* Attribute identifiers */
   hid_t   attr;
   hid_t   aid1, aid2, aid3;    /* Attribute dataspace identifiers */ 
   hid_t   atype;               /* Attribute type */

   hsize_t fdim[] = {SIZE};
   hsize_t adim[] = {ADIM1, ADIM2};  /* Dimensions of the first attribute  */
   
   float matrix[ADIM1][ADIM2]; /* Attribute data */ 

   herr_t  ret;                /* Return value */
   uint    i,j;                /* Counters */
   int     idx;                /* Attribute index */
   char    string_out[80];     /* Buffer to read string attribute back */
   int     point_out;          /* Buffer to read scalar attribute back */

   /*
    * Data initialization.
    */
   int vector[] = {1, 2, 3, 4, 5, 6, 7};  /* Dataset data */
   int point = 1;                         /* Value of the scalar attribute */ 
   char string[] = "ABCD";                /* Value of the string attribute */

   
   for (i=0; i < ADIM1; i++) {            /* Values of the array attribute */
       for (j=0; j < ADIM2; j++)
       matrix[i][j] = -1.;
   }

   /*
    * Create a file.
    */
   file = H5Fcreate(FILE, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

   /* 
    * Create the dataspace for the dataset in the file.
    */
   fid = H5Screate(H5S_SIMPLE);
   ret = H5Sset_extent_simple(fid, RANK, fdim, NULL);

   /*
    * Create the dataset in the file.
    */
   dataset = H5Dcreate(file, "Dataset", H5T_NATIVE_INT, fid, H5P_DEFAULT);

   /*
    * Write data to the dataset.
    */
   ret = H5Dwrite(dataset, H5T_NATIVE_INT, H5S_ALL , H5S_ALL, H5P_DEFAULT, vector);

   /*
    * Create dataspace for the first attribute. 
    */
   aid1 = H5Screate(H5S_SIMPLE);
   ret  = H5Sset_extent_simple(aid1, ARANK, adim, NULL);

   /*
    * Create array attribute.
    */
   attr1 = H5Acreate(dataset, ANAME, H5T_NATIVE_FLOAT, aid1, H5P_DEFAULT);

   /*
    * Write array attribute.
    */
   ret = H5Awrite(attr1, H5T_NATIVE_FLOAT, matrix);

   /*
    * Create scalar attribute.
    */
   aid2  = H5Screate(H5S_SCALAR);
   attr2 = H5Acreate(dataset, "Integer attribute", H5T_NATIVE_INT, aid2,
                     H5P_DEFAULT);

   /*
    * Write scalar attribute.
    */
   ret = H5Awrite(attr2, H5T_NATIVE_INT, &point); 

   /*
    * Create string attribute.
    */
   aid3  = H5Screate(H5S_SCALAR);
   atype = H5Tcopy(H5T_C_S1);
           H5Tset_size(atype, 4);
   attr3 = H5Acreate(dataset, ANAMES, atype, aid3, H5P_DEFAULT);

   /*
    * Write string attribute.
    */
   ret = H5Awrite(attr3, atype, string); 

   /*
    * Close attribute and file dataspaces.
    */
   ret = H5Sclose(aid1); 
   ret = H5Sclose(aid2); 
   ret = H5Sclose(aid3); 
   ret = H5Sclose(fid); 

   /*
    * Close the attributes.
    */ 
   ret = H5Aclose(attr1);
   ret = H5Aclose(attr2);
   ret = H5Aclose(attr3);
 
   /*
    * Close the dataset.
    */
   ret = H5Dclose(dataset);

   /*
    * Close the file.
    */
   ret = H5Fclose(file);

   /*
    * Reopen the file.
    */
   file = H5Fopen(FILE, H5F_ACC_RDONLY, H5P_DEFAULT);

   /*
    * Open the dataset.
    */
   dataset = H5Dopen(file,"Dataset");

   /*
    * Attach to the scalar attribute using attribute name, then read and 
    * display its value.
    */
   attr = H5Aopen_name(dataset,"Integer attribute");
   ret  = H5Aread(attr, H5T_NATIVE_INT, &point_out);
   printf("The value of the attribute \"Integer attribute\" is %d \n", point_out); 
   ret =  H5Aclose(attr);

   /*
    * Attach to the string attribute using its index, then read and display the value.
    */
   attr  = H5Aopen_idx(dataset, 2);
   atype = H5Tcopy(H5T_C_S1);
           H5Tset_size(atype, 4);
   ret   = H5Aread(attr, atype, string_out);
   printf("The value of the attribute with the index 2 is %s \n", string_out);
   ret   = H5Aclose(attr);
   ret   = H5Tclose(atype);

   /*
    * Get attribute info using iteration function. 
    */
   idx = H5Aiterate(dataset, NULL, attr_info, NULL);

   /*
    * Close the dataset and the file.
    */
   H5Dclose(dataset);
   H5Fclose(file);

   return 0;  
}

/*
 * Operator function.
 */
herr_t 
attr_info(hid_t loc_id, const char *name, void *opdata)
{
    hid_t attr, atype, aspace;  /* Attribute, datatype and dataspace identifiers */
    int   rank;
    hsize_t sdim[64]; 
    herr_t ret;
    int i;
    size_t npoints;             /* Number of elements in the array attribute. */ 
    float *float_array;         /* Pointer to the array attribute. */
    /*
     * Open the attribute using its name.
     */    
    attr = H5Aopen_name(loc_id, name);

    /*
     * Display attribute name.
     */
    printf("\n");
    printf("Name : ");
    puts(name);

    /* 
     * Get attribute datatype, dataspace, rank, and dimensions.
     */
    atype  = H5Aget_type(attr);
    aspace = H5Aget_space(attr);
    rank = H5Sget_simple_extent_ndims(aspace);
    ret = H5Sget_simple_extent_dims(aspace, sdim, NULL);

    /*
     *  Display rank and dimension sizes for the array attribute.
     */

    if(rank > 0) {
    printf("Rank : %d \n", rank); 
    printf("Dimension sizes : ");
    for (i=0; i< rank; i++) printf("%d ", (int)sdim[i]);
    printf("\n");
    }

    /*
     * Read array attribute and display its type and values.
     */

    if (H5T_FLOAT == H5Tget_class(atype)) {
    printf("Type : FLOAT \n"); 
    npoints = H5Sget_simple_extent_npoints(aspace);
    float_array = (float *)malloc(sizeof(float)*(int)npoints); 
    ret = H5Aread(attr, atype, float_array);
    printf("Values : ");
    for( i = 0; i < (int)npoints; i++) printf("%f ", float_array[i]); 
    printf("\n");
    free(float_array);
    }

    /*
     * Release all identifiers.
     */
    H5Tclose(atype);
    H5Sclose(aspace);
    H5Aclose(attr);

    return 0;
}

Example 9. Creating and storing references to objects.

This example creates a group and two datasets and a named datatype in the group. References to these four objects are stored in the dataset in the root group.

#include <hdf5.h>

#define FILE1   "trefer1.h5"

/* 1-D dataset with fixed dimensions */
#define SPACE1_NAME  "Space1"
#define SPACE1_RANK	1
#define SPACE1_DIM1	4

/* 2-D dataset with fixed dimensions */
#define SPACE2_NAME  "Space2"
#define SPACE2_RANK	2
#define SPACE2_DIM1	10
#define SPACE2_DIM2	10

int 
main(void) {
    hid_t		fid1;		/* HDF5 File IDs		*/
    hid_t		dataset;	/* Dataset ID			*/
    hid_t		group;      /* Group ID             */
    hid_t		sid1;       /* Dataspace ID			*/
    hid_t		tid1;       /* Datatype ID			*/
    hsize_t		dims1[] = {SPACE1_DIM1};
    hobj_ref_t      *wbuf;      /* buffer to write to disk */
    int       *tu32;      /* Temporary pointer to int data */
    int        i;          /* counting variables */
    const char *write_comment="Foo!"; /* Comments for group */
    herr_t		ret;		/* Generic return value		*/

/* Compound datatype */
typedef struct s1_t {
    unsigned int a;
    unsigned int b;
    float c;
} s1_t;

    /* Allocate write buffers */
    wbuf=(hobj_ref_t *)malloc(sizeof(hobj_ref_t)*SPACE1_DIM1);
    tu32=malloc(sizeof(int)*SPACE1_DIM1);

    /* Create file */
    fid1 = H5Fcreate(FILE1, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

    /* Create dataspace for datasets */
    sid1 = H5Screate_simple(SPACE1_RANK, dims1, NULL);

    /* Create a group */
    group=H5Gcreate(fid1,"Group1",-1);

    /* Set group's comment */
    ret=H5Gset_comment(group,".",write_comment);

    /* Create a dataset (inside Group1) */
    dataset=H5Dcreate(group,"Dataset1",H5T_STD_U32LE,sid1,H5P_DEFAULT);

    for(i=0; i < SPACE1_DIM1; i++)
        tu32[i] = i*3;

    /* Write selection to disk */
    ret=H5Dwrite(dataset,H5T_NATIVE_INT,H5S_ALL,H5S_ALL,H5P_DEFAULT,tu32);

    /* Close Dataset */
    ret = H5Dclose(dataset);

    /* Create another dataset (inside Group1) */
    dataset=H5Dcreate(group,"Dataset2",H5T_NATIVE_UCHAR,sid1,H5P_DEFAULT);

    /* Close Dataset */
    ret = H5Dclose(dataset);

    /* Create a datatype to refer to */
    tid1 = H5Tcreate (H5T_COMPOUND, sizeof(s1_t));

    /* Insert fields */
    ret=H5Tinsert (tid1, "a", HOFFSET(s1_t,a), H5T_NATIVE_INT);

    ret=H5Tinsert (tid1, "b", HOFFSET(s1_t,b), H5T_NATIVE_INT);

    ret=H5Tinsert (tid1, "c", HOFFSET(s1_t,c), H5T_NATIVE_FLOAT);

    /* Save datatype for later */
    ret=H5Tcommit (group, "Datatype1", tid1);

    /* Close datatype */
    ret = H5Tclose(tid1);

    /* Close group */
    ret = H5Gclose(group);

    /* Create a dataset to store references */
    dataset=H5Dcreate(fid1,"Dataset3",H5T_STD_REF_OBJ,sid1,H5P_DEFAULT);

    /* Create reference to dataset */
    ret = H5Rcreate(&wbuf[0],fid1,"/Group1/Dataset1",H5R_OBJECT,-1);

    /* Create reference to dataset */
    ret = H5Rcreate(&wbuf[1],fid1,"/Group1/Dataset2",H5R_OBJECT,-1);

    /* Create reference to group */
    ret = H5Rcreate(&wbuf[2],fid1,"/Group1",H5R_OBJECT,-1);

    /* Create reference to named datatype */
    ret = H5Rcreate(&wbuf[3],fid1,"/Group1/Datatype1",H5R_OBJECT,-1);

    /* Write selection to disk */
    ret=H5Dwrite(dataset,H5T_STD_REF_OBJ,H5S_ALL,H5S_ALL,H5P_DEFAULT,wbuf);

    /* Close disk dataspace */
    ret = H5Sclose(sid1);
    
    /* Close Dataset */
    ret = H5Dclose(dataset);

    /* Close file */
    ret = H5Fclose(fid1);
    free(wbuf);
    free(tu32);
    return 0;
}

Example 10. Reading references to objects.

This example opens and reads dataset Dataset3 from the file created in Example 9. Then the program dereferences the references to dataset Dataset1, the group and the named datatype, and opens those objects. The program reads and displays the dataset's data, the group's comment, and the number of members of the compound datatype.

#include <stdlib.h>
#include <hdf5.h>

#define FILE1   "trefer1.h5"

/* dataset with fixed dimensions */
#define SPACE1_NAME  "Space1"
#define SPACE1_RANK	1
#define SPACE1_DIM1	4

int 
main(void)
{
    hid_t		fid1;		/* HDF5 File IDs		*/
    hid_t		dataset,	/* Dataset ID			*/
                dset2;      /* Dereferenced dataset ID */
    hid_t		group;      /* Group ID             */
    hid_t		sid1;       /* Dataspace ID			*/
    hid_t		tid1;       /* Datatype ID			*/
    hobj_ref_t      *rbuf;      /* buffer to read from disk */
    int                *tu32;      /* temp. buffer read from disk */
    int        i;          /* counting variables */
    char read_comment[10];
    herr_t		ret;		/* Generic return value		*/

    /* Allocate read buffers */
    rbuf = malloc(sizeof(hobj_ref_t)*SPACE1_DIM1);
    tu32 = malloc(sizeof(int)*SPACE1_DIM1);

    /* Open the file */
    fid1 = H5Fopen(FILE1, H5F_ACC_RDWR, H5P_DEFAULT);

    /* Open the dataset */
    dataset=H5Dopen(fid1,"/Dataset3");

    /* Read selection from disk */
    ret=H5Dread(dataset,H5T_STD_REF_OBJ,H5S_ALL,H5S_ALL,H5P_DEFAULT,rbuf);

    /* Open dataset object */
    dset2 = H5Rdereference(dataset,H5R_OBJECT,&rbuf[0]);

    /* Check information in referenced dataset */
    sid1 = H5Dget_space(dset2);

    ret=H5Sget_simple_extent_npoints(sid1);

    /* Read from disk */
    ret=H5Dread(dset2,H5T_NATIVE_INT,H5S_ALL,H5S_ALL,H5P_DEFAULT,tu32);
    printf("Dataset data : \n");
     for (i=0; i < SPACE1_DIM1 ; i++) printf (" %d ", tu32[i]);
    printf("\n");
    printf("\n");

    /* Close dereferenced Dataset */
    ret = H5Dclose(dset2);

    /* Open group object */
    group = H5Rdereference(dataset,H5R_OBJECT,&rbuf[2]);

    /* Get group's comment */
    ret=H5Gget_comment(group,".",10,read_comment);
    printf("Group comment is %s \n", read_comment);
    printf(" \n");
    /* Close group */
    ret = H5Gclose(group);

    /* Open datatype object */
    tid1 = H5Rdereference(dataset,H5R_OBJECT,&rbuf[3]);

    /* Verify correct datatype */
    {
        H5T_class_t tclass;

        tclass= H5Tget_class(tid1);
        if ((tclass == H5T_COMPOUND))
           printf ("Number of compound datatype members is %d \n", H5Tget_nmembers(tid1)); 
    printf(" \n");
    }

    /* Close datatype */
    ret = H5Tclose(tid1);

    /* Close Dataset */
    ret = H5Dclose(dataset);

    /* Close file */
    ret = H5Fclose(fid1);

    /* Free memory buffers */
    free(rbuf);
    free(tu32);
    return 0;
}   

Example 11. Creating and writing a reference to a region.

This example creates a dataset in the file. Then it creates a dataset to store references to the dataset regions (selections). The first selection is a 6 x 6 hyperslab. The second selection is a point selection in the same dataset. References to both selections are created and stored in the buffer, and then written to the dataset in the file.
#include <stdlib.h>
#include <hdf5.h>

#define FILE2	"trefer2.h5"
#define SPACE1_NAME  "Space1"
#define SPACE1_RANK     1
#define SPACE1_DIM1     4

/* Dataset with fixed dimensions */
#define SPACE2_NAME  "Space2"
#define SPACE2_RANK	2
#define SPACE2_DIM1	10
#define SPACE2_DIM2	10

/* Element selection information */
#define POINT1_NPOINTS 10

int
main(void)
{
    hid_t		fid1;		/* HDF5 File IDs		*/
    hid_t		dset1,	/* Dataset ID			*/
                dset2;      /* Dereferenced dataset ID */
    hid_t		sid1,       /* Dataspace ID	#1		*/
                sid2;       /* Dataspace ID	#2		*/
    hsize_t		dims1[] = {SPACE1_DIM1},
            	dims2[] = {SPACE2_DIM1, SPACE2_DIM2};
    hssize_t	start[SPACE2_RANK];     /* Starting location of hyperslab */
    hsize_t		stride[SPACE2_RANK];    /* Stride of hyperslab */
    hsize_t		count[SPACE2_RANK];     /* Element count of hyperslab */
    hsize_t		block[SPACE2_RANK];     /* Block size of hyperslab */
    hssize_t	coord1[POINT1_NPOINTS][SPACE2_RANK]; 
                                    /* Coordinates for point selection */
    hdset_reg_ref_t      *wbuf;      /* buffer to write to disk */
    int     *dwbuf;      /* Buffer for writing numeric data to disk */
    int        i;          /* counting variables */
    herr_t		ret;		/* Generic return value		*/


    /* Allocate write & read buffers */
    wbuf=calloc(sizeof(hdset_reg_ref_t), SPACE1_DIM1);
    dwbuf=malloc(sizeof(int)*SPACE2_DIM1*SPACE2_DIM2);

    /* Create file */
    fid1 = H5Fcreate(FILE2, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

    /* Create dataspace for datasets */
    sid2 = H5Screate_simple(SPACE2_RANK, dims2, NULL);

    /* Create a dataset */
    dset2=H5Dcreate(fid1,"Dataset2",H5T_STD_U8LE,sid2,H5P_DEFAULT);

    for(i=0; i < SPACE2_DIM1*SPACE2_DIM2; i++)
        dwbuf[i]=i*3;

    /* Write selection to disk */
    ret=H5Dwrite(dset2,H5T_NATIVE_INT,H5S_ALL,H5S_ALL,H5P_DEFAULT,dwbuf);

    /* Close Dataset */
    ret = H5Dclose(dset2);

    /* Create dataspace for the reference dataset */
    sid1 = H5Screate_simple(SPACE1_RANK, dims1, NULL);

    /* Create a dataset */
    dset1=H5Dcreate(fid1,"Dataset1",H5T_STD_REF_DSETREG,sid1,H5P_DEFAULT);

    /* Create references */

    /* Select 6x6 hyperslab for first reference */
    start[0]=2; start[1]=2;
    stride[0]=1; stride[1]=1;
    count[0]=6; count[1]=6;
    block[0]=1; block[1]=1;
    ret = H5Sselect_hyperslab(sid2,H5S_SELECT_SET,start,stride,count,block);

    /* Store first dataset region */
    ret = H5Rcreate(&wbuf[0],fid1,"/Dataset2",H5R_DATASET_REGION,sid2);

    /* Select sequence of ten points for second reference */
    coord1[0][0]=6; coord1[0][1]=9;
    coord1[1][0]=2; coord1[1][1]=2;
    coord1[2][0]=8; coord1[2][1]=4;
    coord1[3][0]=1; coord1[3][1]=6;
    coord1[4][0]=2; coord1[4][1]=8;
    coord1[5][0]=3; coord1[5][1]=2;
    coord1[6][0]=0; coord1[6][1]=4;
    coord1[7][0]=9; coord1[7][1]=0;
    coord1[8][0]=7; coord1[8][1]=1;
    coord1[9][0]=3; coord1[9][1]=3;
    ret = H5Sselect_elements(sid2,H5S_SELECT_SET,POINT1_NPOINTS,(const hssize_t **)coord1);

    /* Store second dataset region */
    ret = H5Rcreate(&wbuf[1],fid1,"/Dataset2",H5R_DATASET_REGION,sid2);

    /* Write selection to disk */
    ret=H5Dwrite(dset1,H5T_STD_REF_DSETREG,H5S_ALL,H5S_ALL,H5P_DEFAULT,wbuf);

    /* Close all objects */
    ret = H5Sclose(sid1);
    ret = H5Dclose(dset1);
    ret = H5Sclose(sid2);
    
    /* Close file */
    ret = H5Fclose(fid1);

    free(wbuf);
    free(dwbuf);
    return 0;
}   

Example 12. Reading a reference to a region.

This example reads a dataset containing dataset region references. It reads data from the dereferenced dataset and displays the number of elements and raw data. Then it reads two selections: a hyperslab selection and a point selection. The program queries a number of points in the hyperslab and the coordinates and displays them. Then it queries a number of selected points and their coordinates and displays the information.
   
#include <stdlib.h>
#include <hdf5.h>

#define FILE2	"trefer2.h5"
#define NPOINTS 10
 
/* 1-D dataset with fixed dimensions */
#define SPACE1_NAME  "Space1"
#define SPACE1_RANK	1
#define SPACE1_DIM1	4

/* 2-D dataset with fixed dimensions */
#define SPACE2_NAME  "Space2"
#define SPACE2_RANK	2
#define SPACE2_DIM1	10
#define SPACE2_DIM2	10

int 
main(void)
{
    hid_t		fid1;		/* HDF5 File IDs		*/
    hid_t		dset1,	/* Dataset ID			*/
                dset2;      /* Dereferenced dataset ID */
    hid_t		sid1,       /* Dataspace ID	#1		*/
                sid2;       /* Dataspace ID	#2		*/
    hsize_t *   coords;             /* Coordinate buffer */
    hsize_t		low[SPACE2_RANK];   /* Selection bounds */
    hsize_t		high[SPACE2_RANK];     /* Selection bounds */
    hdset_reg_ref_t      *rbuf;      /* buffer to to read disk */
    int    *drbuf;      /* Buffer for reading numeric data from disk */
    int        i, j;          /* counting variables */
    herr_t		ret;		/* Generic return value		*/

    /* Output message about test being performed */

    /* Allocate write & read buffers */
    rbuf=malloc(sizeof(hdset_reg_ref_t)*SPACE1_DIM1);
    drbuf=calloc(sizeof(int),SPACE2_DIM1*SPACE2_DIM2);

    /* Open the file */
    fid1 = H5Fopen(FILE2, H5F_ACC_RDWR, H5P_DEFAULT);

    /* Open the dataset */
    dset1=H5Dopen(fid1,"/Dataset1");

    /* Read selection from disk */
    ret=H5Dread(dset1,H5T_STD_REF_DSETREG,H5S_ALL,H5S_ALL,H5P_DEFAULT,rbuf);

    /* Try to open objects */
    dset2 = H5Rdereference(dset1,H5R_DATASET_REGION,&rbuf[0]);

    /* Check information in referenced dataset */
    sid1 = H5Dget_space(dset2);

    ret=H5Sget_simple_extent_npoints(sid1);
    printf(" Number of elements in the dataset is : %d\n",ret);

    /* Read from disk */
    ret=H5Dread(dset2,H5T_NATIVE_INT,H5S_ALL,H5S_ALL,H5P_DEFAULT,drbuf);

    for(i=0; i < SPACE2_DIM1; i++) {
        for (j=0; j < SPACE2_DIM2; j++) printf (" %d ", drbuf[i*SPACE2_DIM2+j]);
        printf("\n"); }

    /* Get the hyperslab selection */
    sid2=H5Rget_region(dset1,H5R_DATASET_REGION,&rbuf[0]);

    /* Verify correct hyperslab selected */
    ret = H5Sget_select_npoints(sid2);
    printf(" Number of elements in the hyperslab is : %d \n", ret);
    ret = H5Sget_select_hyper_nblocks(sid2);
    coords=malloc(ret*SPACE2_RANK*sizeof(hsize_t)*2); /* allocate space for the hyperslab blocks */
    ret = H5Sget_select_hyper_blocklist(sid2,0,ret,coords);
    printf(" Hyperslab coordinates are : \n");
    printf (" ( %lu , %lu ) ( %lu , %lu ) \n", \
(unsigned long)coords[0],(unsigned long)coords[1],(unsigned long)coords[2],(unsigned long)coords[3]); 
    free(coords);
    ret = H5Sget_select_bounds(sid2,low,high);

    /* Close region space */
    ret = H5Sclose(sid2);

    /* Get the element selection */
    sid2=H5Rget_region(dset1,H5R_DATASET_REGION,&rbuf[1]);

    /* Verify correct elements selected */
    ret = H5Sget_select_elem_npoints(sid2);
    printf(" Number of selected elements is : %d\n", ret);

    /* Allocate space for the element points */
    coords= malloc(ret*SPACE2_RANK*sizeof(hsize_t)); 
    ret = H5Sget_select_elem_pointlist(sid2,0,ret,coords);
    printf(" Coordinates of selected elements are : \n");
    for (i=0; i < 2*NPOINTS; i=i+2) 
         printf(" ( %lu , %lu ) \n", (unsigned long)coords[i],(unsigned long)coords[i+1]); 
          
    free(coords);
    ret = H5Sget_select_bounds(sid2,low,high);

    /* Close region space */
    ret = H5Sclose(sid2);

    /* Close first space */
    ret = H5Sclose(sid1);

    /* Close dereferenced Dataset */
    ret = H5Dclose(dset2);

    /* Close Dataset */
    ret = H5Dclose(dset1);

    /* Close file */
    ret = H5Fclose(fid1);

    /* Free memory buffers */
    free(rbuf);
    free(drbuf);
    return 0;
}   

 

(Return to TOC)


Introduction to HDF5 
HDF5 User Guide 
HDF5 Reference Manual 
Other HDF5 documents and links 

HDF Help Desk
Last modified: 16 October 1999
Copyright