14

I am opening an existing HDF5 file for appending data; I want to assure that group called /A exists for subsequent access. I am looking for an easy way to either create /A conditionally (create and return new group if not existing, or return the existing group). One way is to test for /A existence. How can I do it efficiently?

According to the API docs, I can do something like this:

H5::H5File h5file(filename,H5F_ACC_RDWR);
H5::H5Group grp;
try{
   grp=h5file.openGroup("A");
} catch(H5::Exception& e){
   /* group does not exists, create it */
   grp=h5file.createGroup("A");
}

but the obvious ugliness comes from the fact that exception is used to communicate information which is not exceptional at all.

There is H5::CommonFG::getObjinfo, which seems to wrap H5Gget_objinfo in such way that false (nonexistent) return value of the C routine throws an exception; so again the same problem.

Is it clean to recourse to the C API in this case, or is there some function directly designed to test existence in the C++ API which I am overlooking?

eudoxos
  • 18,545
  • 10
  • 61
  • 110
  • It looks like the C++ equivalent of [`H5Lexists`](https://www.hdfgroup.org/HDF5/doc/RM/RM_H5L.html#Link-Exists) doesn't exist at all. The `try ... catch ...` seems much more pythonic than C++ to me, but I think that or using the C API are your two options. – Yossarian Mar 14 '16 at 09:43

3 Answers3

4

As suggested by Yossarian in his comment and in this answer you can use HDF5 1.8.0+ C-API

bool pathExists(hid_t id, const std::string& path)
{
  return H5Lexists( id, path.c_str(), H5P_DEFAULT ) > 0;
}

H5::H5File h5file(filename,H5F_ACC_RDWR);
H5::H5Group grp;
if (pathExists(h5file.getId(), "A")) 
   grp=h5file.openGroup("A");
else
   grp=h5file.createGroup("A");
Peter Petrik
  • 9,701
  • 5
  • 41
  • 65
1

Since none of the solutions worked for me, here what I did.

H5:H5File file(filename, H5F_ACC_RWWR);
...
if(file.nameExists(groupname))
   return file.openGroup(groupname);
else
   return file.createGroup(groupname);       
Stalex
  • 11
  • 1
0

I am testing the existence of a group with:

bool H5Location::attrExists(const char* name) const;

That way you can test the existence of group/dataset/… at the specified location.

// Test if empty (= new) H5 file
auto isNewFile = this->attrExists(VariablesH5GroupName);
Salamandar
  • 589
  • 6
  • 16
  • Not 100% what I needed (I still have to check if it is a group and not some other attribute) but seems as good as it can get. Thanks! – eudoxos Jan 05 '17 at 13:22
  • 3
    Actually this only works if the group has a named attribute and that's not always the case… So it's not a correct answer, sorry :/ – Salamandar Jan 05 '17 at 14:31
  • Just tried; with plain dataset, it will return false even if the dataset exists. Perhaps mark it more visible in the answer itself that it is not a correct one. – eudoxos Dec 30 '19 at 09:44