将3D数据写入C中的HDF5文件

Write 3D data into HDF5 file in C

我正在尝试使用 hyper slab 将像线性阵列 () 一样存储在内存中的三维数据 () 写入 HDF5 文件。请参阅下面的代码:

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <float.h>

#include "hdf5.h"

int main(int argc, char *argv[])
{
    int i, j, k;
    int count = 0;
    int Nx = 180;
    int Ny = 128;
    int Nz = 128;

    double *data = (double *)malloc(Nx * Ny * Nz * sizeof(double));

    for (i = 0; i < Nx; i++)
    {
        for (j = 0; j < Ny; j++)
        {
            for (k = 0; k < Nz; k++)
            {
                data[k + Nz * j + Nz * Ny * i] = (double)count;
                count++;
            }
        }
    }

    hid_t err;
    hid_t dataspace, memspace, dataset;
    hid_t file_identifier;
    int rank;
    hsize_t dimens_3d[3];
    hsize_t start_3d[3];
    hsize_t stride_3d[3];
    hsize_t count_3d[3];

    char *file_name = "data.h5";

    file_identifier = H5Fcreate(file_name, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

    rank = 3;

    dimens_3d[0] = Nz;
    dimens_3d[1] = Ny;
    dimens_3d[2] = Nx;

    dataspace = H5Screate_simple(rank, dimens_3d, NULL);

    start_3d[0] = 0;
    start_3d[1] = 0;
    start_3d[2] = 0;

    stride_3d[0] = 1;
    stride_3d[1] = 1;
    stride_3d[1] = 1;

    count_3d[0] = Nz;
    count_3d[1] = Ny;
    count_3d[2] = Nx;

    err = H5Sselect_hyperslab(dataspace, H5S_SELECT_SET, start_3d, stride_3d, count_3d, NULL);

    dimens_3d[0] = Nz;
    dimens_3d[1] = Ny;
    dimens_3d[2] = Nx;

    memspace = H5Screate_simple(rank, dimens_3d, NULL);

    start_3d[0] = 0;
    start_3d[1] = 0;
    start_3d[2] = 0;

    stride_3d[0] = 1;
    stride_3d[1] = 1;
    stride_3d[1] = 1;

    count_3d[0] = Nz;
    count_3d[1] = Ny;
    count_3d[2] = Nx;

    err = H5Sselect_hyperslab(memspace, H5S_SELECT_SET, start_3d, stride_3d, count_3d, NULL);

    dataset = H5Dcreate(file_identifier, "data", H5T_NATIVE_DOUBLE, dataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);

    err = H5Dwrite(dataset, H5T_NATIVE_DOUBLE, memspace, dataspace, H5P_DEFAULT, &(data[0]));

    H5Sclose(memspace);
    H5Sclose(dataspace);
    H5Dclose(dataset);

    H5Fclose(file_identifier);

    free(data);

    return 0;
}

此示例未将任何数据放入文件中,我不明白为什么。该文件已创建,但当我使用 h5dump 实用程序 (h5dump -u data.h5 > data.xml) 将其转储到 XML 文件时,data 数组没有值。如果我注释行 H5Sselect_hyperslab 函数值出现在文件中。

我知道这里没有必要使用 H5Sselect_hyperslab 函数,但我的下一步是并行编写 HDF5,其中需要使用 hyper slab。

您在 stride_3d 中输入错误:您设置了两次 stride_3d[1] 而从未设置 stride_3d[2] 因此 stride_3d[2] 的初始值未定义(a.k.a . 垃圾)并且对 H5Sselect_hyperslab 的调用失败。这就引出了我的第二点……

检查您的错误!您应该在每次 API 调用后检查 err 的值。