hdf5:选中以创建组

时间:2017-06-05 15:16:57

标签: c++ hdf5

如果某个组尚不存在,我想自动创建一个组。但是我没有成功检查该组是否存在。

尝试失败1

#include <iostream>
#include <string>
#include "H5Cpp.h"

int main(void)
{
  H5::H5File file("test.h5",H5F_ACC_TRUNC);

  std::string group_name = "/test";

  H5::Group group = file.createGroup(group_name.c_str());

  if ( !file.attrExists(group_name.c_str()) )
    H5::Group group = file.createGroup(group_name.c_str());

  return 0;
}

使用

进行编译
$ h5c++ -o test test.cpp

失败,因为file.attrExists(name)始终返回false。作为参考,错误发生在createGroup

... 

#006: H5L.c line 1733 in H5L_link_cb(): name already exists
  major: Symbol table
  minor: Object already exists

尝试失败2

#include <iostream>
#include <string>
#include "H5Cpp.h"

int main(void)
{
  H5::H5File file("test.h5",H5F_ACC_TRUNC);

  std::string group_name = "/test";

  try         { H5::Group group = file.openGroup  (group_name.c_str()); }
  catch (...) { H5::Group group = file.createGroup(group_name.c_str()); }

  return 0;
}

使用

进行编译
$ h5c++ -o test test.cpp

不知何故,catch不成功,openGroup失败时会产生错误:

...

#005: H5Gloc.c line 385 in H5G_loc_find_cb(): object 'test' doesn't exist
  major: Symbol table
  minor: Object not found

1 个答案:

答案 0 :(得分:1)

您的尝试1 失败,因为H5::Group不是属性,所以

if ( !file.attrExists(group_name.c_str()) )

不是你想的那样。 AFAIK,没有比试图打开它更简单的方法来检查组的存在。这导致我们

你的尝试2 实际上没有失败,但有效(你为什么不这么认为?)不幸的是,HDF5吐出了很多错误模糊(除了抛出例外),但你可以压制

int main(void)
{
  H5::Exception::dontPrint();                             // suppress error messages
  H5::H5File file("test.h5",H5F_ACC_TRUNC);    
  std::string group_name = "/test";
  try         {
    H5::Group group = file.openGroup  (group_name.c_str());
    std::cerr<<" TEST: opened group\n";                   // for debugging
  } catch (...) {
    std::cerr<<" TEST: caught something\n";               // for debugging
    H5::Group group = file.createGroup(group_name.c_str());
    std::cerr<<" TEST: created group\n";                  // for debugging
  }
  H5::Group group = file.openGroup  (group_name.c_str()); // for debugging
  std::cerr<<" TEST: opened group\n";                     // for debugging
}

产生

  

TEST:抓住了一些东西   测试:创建组
  测试:打开小组