【问题标题】:hdf5: Check to create grouphdf5:检查以创建组
【发布时间】:2017-11-06 10:00:24
【问题描述】:

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

尝试 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

【问题讨论】:

  • 如果在“/test”(group_name)中省略“/”会怎样?
  • @Walter 感谢您的建议,但它不能解决两个提议的解决方案中的任何一个。您能解释一下为什么您认为删除第一个斜线会有所帮助吗?

标签: c++ hdf5


【解决方案1】:

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

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

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

您的尝试 2 实际上没有失败,但是有效(您为什么不这么认为?)不幸的是,HDF5 吐出了很多错误信息(除了 throw一个例外),但你可以抑制它

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
}

生成

测试:抓到东西
测试:创建组
测试:开组

【讨论】:

  • 谢谢。我确实被“错误简介”吓到了。
猜你喜欢
  • 2011-03-29
  • 1970-01-01
  • 2016-05-18
  • 1970-01-01
  • 2015-05-14
  • 2012-03-31
  • 2011-06-15
  • 2017-04-27
  • 1970-01-01
相关资源
最近更新 更多