实例2 在指定文件下创建一个数据集(创建文件,组,详情看:hdf5实例1)
在已有hdf5文件file.h5 root下,创建一个名字为dset1 , rank为2,dims 大小为4*4 数据集
代码思路:
- 打开需要操作的文件
- 创建数据空间
- 创建数据集
- 初始化数据
- 写入数据
- 读出数据
- 关闭资源
/*Create a dataset under root
*The dataset name is dset1,rank is 2 ,dimensions is 4*4
*The file name is dset.h5
*/
#include "hdf5.h"
#define FILENAME "dset.h5"
#define DSETNAME "dset1"
#define RANK 2
int main(){
hid_t file,dataspace,dset;
herr_t status;
hsize_t dims[2];
file = H5Fopen("file.h5", H5F_ACC_RDWR, H5P_DEFAULT);
int nx=4;
int ny=4;
dims[0] = nx;
dims[1] = ny;
dataspace = H5Screate_simple(RANK,dims, NULL);
dset = H5Dcreate(file, DSETNAME ,H5T_NATIVE_INT, dataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
//intinalize data
int i,j,data[nx][ny];
for(i=0;i<nx;i++){
for(j=0;j<ny;j++)
data[i][j] = i+j;
}
status = H5Dwrite(dset,H5T_NATIVE_INT,H5S_ALL,H5S_ALL, H5P_DEFAULT, data);
//read data from dset1: test write data successful
status = H5Dread(dset,H5T_NATIVE_INT,H5S_ALL,H5S_ALL, H5P_DEFAULT, data);
printf ("Read data from dset1:\n");
for(i=0;i<nx;i++){
for(j=0;j<ny;j++)
printf("%3d",data[i][j]);
printf("\n");
}
H5Sclose(dataspace);
H5Dclose(dset);
H5Fclose(file);
}