一个HDF5文件中有多少个数据集

How many datasets in one hdf5 file

本文关键字:多少 数据集 HDF5 文件 一个      更新时间:2023-10-16

我正在使用MATLAB的函数H5Write将Double变量foo写入称为saved_foos.h5的HDF5文件。我有一个循环,可以在每次迭代中更改foo,并且每次将其保存在同一HDF5文件中,但在另一个数据集中,该数据集是根据当前迭代次数命名的。

之后,我在带有H5Cpp库的C 程序中读取了每个数据集(EAACH迭代(的数据,如下所示:

#include "H5Cpp.h"
using namespace H5;
double readDouble(std::string dir, std::string file, std::string s_dataset) {
    if (!fexists((dir + file + std::string(".h5")).c_str())) {
        throw std::runtime_error((std::string("File ") + dir + file + std::string(".h5 does not exist.")).c_str());
    }
    H5File file_h(dir + file + std::string(".h5"), H5F_ACC_RDONLY);
    DataSet dataset = file_h.openDataSet(s_dataset);
    DataSpace dataspace = dataset.getSpace();
    int rank = dataspace.getSimpleExtentNdims();
    hsize_t *dims_out = new hsize_t[rank];
    dataspace.getSimpleExtentDims(dims_out, NULL);
    if (rank>=2 && (dims_out[0] * dims_out[1] != 1)) {
        throw std::runtime_error("Requested dataset is not a scalar double value.");
    }
    double data;
    dataset.read(&data, PredType::NATIVE_DOUBLE);
    delete dims_out;
    return data;
}

但是如何确定在给定的HDF5文件中存储了多少个数据集?

遍历文件

似乎您要列出文件中的数据集。这是一个非常完整的示例,这是您问题的过度杀伤。为了帮助理解它,我将解释相关的代码会话:

C-API函数H5Literate用于迭代组中的所有对象。

/*
 * Use iterator to see the names of the objects in the file
 * root directory.
 */
cout << endl << "Iterating over elements in the file" << endl;
herr_t idx = H5Literate(file->getId(), H5_INDEX_NAME, H5_ITER_INC, NULL,    file_info, NULL);
cout << endl;

其中 file_info是回调函数:

/*
 * Operator function.
 */
herr_t
file_info(hid_t loc_id, const char *name, const H5L_info_t *linfo, void *opdata)
{
    hid_t group;
    group = H5Gopen2(loc_id, name, H5P_DEFAULT);
    cout << "Name : " << name << endl; // Display the group name.
    H5Gclose(group);
    return 0;
}

在您的情况下,其他迭代功能而不是H5Literate可能更合适。请在这里找到。一个纯C-API示例,可以在此处找到遍历文件。

只获取数字

如果所有数据集都存储在根下,并且其名称的格式已知。有一个更简单的解决方案仅获取数据集数量:

    hsize_t  num_obj;
    H5Gget_num_objs(file->getId(), &num_obj); // if success, num_obj will be assigned the number of objects in the group