HDF5:检查创建组

hdf5: Check to create group

本文关键字:创建组 检查 HDF5      更新时间:2023-10-16

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

失败尝试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 ,由于 H5::Group不是属性而失败,所以

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

不是您认为的。Afaik,没有比试图打开该组的简单方法来检查组的存在。这导致我们

您的尝试2 实际上是没有失败,但是有效(不幸的是,您为什么认为?一个例外(,但是您可以抑制

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 groupn";                   // for debugging
  } catch (...) {
    std::cerr<<" TEST: caught somethingn";               // for debugging
    H5::Group group = file.createGroup(group_name.c_str());
    std::cerr<<" TEST: created groupn";                  // for debugging
  }
  H5::Group group = file.openGroup  (group_name.c_str()); // for debugging
  std::cerr<<" TEST: opened groupn";                     // for debugging
}

生成

测试:捕获的东西
测试:创建组
测试:打开组