Search code examples
c++hdf5

Determine the object type of a HDF5 path


I have a path name (a string) and an open HDF5 file. I have used H5Lexists to ensure an object with that name exists. How do I determine what the object type is? e.g. dataset, group, etc.

// open the file
hid_t fapl = H5Pcreate(H5P_FILE_ACCESS);  
H5Pset_fclose_degree(fapl, H5F_CLOSE_STRONG);
hid_t hid = H5Fopen(filename.c_str(), H5F_ACC_RDONLY, fapl);

// ensure the object exists
const string path = "/some/path/to/an/object";
if (H5Lexists(m_hid, path.c_str(), H5P_DEFAULT) < 0) throw runtime_error();

// determine the object type
// TODO
if (dataset) {
    hid_t dataset = H5Dopen(hid, path.c_str(), H5P_DEFAULT);
    // do something
}
else if (group) {
    hid_t group = H5Gopen(hid, path.c_str(), H5P_DEFAULT);
    // do something
}
H5Fclose(hid);

I am trying not to use the C++ class based interface because this is being added to legacy code. I tried just opening the dataset to see if dataset < 0 to determine if it is a dataset, however, the HDF5 library throws a ton of warnings to stderr, so I'd like to do it the correct way.


Solution

  • Use H5Oopen if you don't know the type in advance and use H5Iget_type to determine it.

    hid_t object = H5Oopen(hid, path.c_str(), H5P_DEFAULT);
    H5I_type_t h5type = H5Iget_type(object);
    
    if (h5type == H5I_BADID) {
        ... // error handling stuff
    } else if (h5type == H5I_DATASET) {
        ... // dataset stuff
    } else if (h5type == H5I_GROUP) {
        ... // group stuff
    } else { // other stuff maybe
    }
    
    H5Oclose(hid);