Test group existence in hdf5/c++

≯℡__Kan透↙ 提交于 2019-12-22 02:03:20

问题


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?


回答1:


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");



回答2:


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);


来源:https://stackoverflow.com/questions/35668056/test-group-existence-in-hdf5-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!