gpt4 book ai didi

c++ - hdf5:勾选创建组

转载 作者:行者123 更新时间:2023-11-30 05:12:44 28 4
gpt4 key购买 nike

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

失败尝试 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 实际上没有失败,但有效(您为什么不这么认为?)不幸的是,HDF5 吐出了很多错误信息(除了抛出一个异常(exception)),但你可以抑制它

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: caught something
TEST: created group
TEST: opened group

关于c++ - hdf5:勾选创建组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44372160/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com