用3D将3D数据写入HDF5文件

时间:2015-12-16 09:08:16

标签: c multidimensional-array hdf5

我尝试使用超级板块将三维数据(Nx x Ny x Nz)写入HDF5文件中,这些数据存储在内存中,如线性数组(k + Nz * j + Nz * Ny * i)。请参阅下面的代码:

#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&gt; data.xml)将其转储到XML文件中时,data数组没有值。如果我对H5Sselect_hyperslab函数值的注释行出现在文件中。

我知道在这里使用H5Sselect_hyperslab函数并不是必需的,但对我来说,下一步将是并行编写HDF5,其中需要使用超级板块。

1 个答案:

答案 0 :(得分:3)

您在stride_3d中输了一个拼写错误:您设置了stride_3d[1]两次并且从未设置stride_3d[2]因此stride_3d[2]的初始值未定义(也称为垃圾)以及调用H5Sselect_hyperslab失败了。这让我们得到了第二点......

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