面试题答案
一键面试program read_hdf5_dataset
use hdf5
implicit none
integer(HID_T) :: file_id, dataset_id
integer :: ierr
integer, parameter :: rank = 1
integer(HID_T) :: dataspace_id
integer(HSIZE_T) :: dims(1)
real :: data(:), data_set1(:)
! 打开HDF5文件
call h5fopen_f('your_file.hdf5', H5F_ACC_RDONLY_F, file_id, ierr)
if (ierr /= 0) then
print *, '无法打开HDF5文件'
stop
end if
! 打开数据集
call h5dopen_f(file_id, 'data_set1', dataset_id, ierr)
if (ierr /= 0) then
print *, '无法打开数据集'
call h5fclose_f(file_id, ierr)
stop
end if
! 获取数据集的空间
call h5dget_space_f(dataset_id, dataspace_id, ierr)
if (ierr /= 0) then
print *, '无法获取数据集空间'
call h5dclose_f(dataset_id, ierr)
call h5fclose_f(file_id, ierr)
stop
end if
! 获取数据集的维度
call h5sget_simple_extent_dims_f(dataspace_id, dims, dims, ierr)
if (ierr /= 0) then
print *, '无法获取数据集维度'
call h5sclose_f(dataspace_id, ierr)
call h5dclose_f(dataset_id, ierr)
call h5fclose_f(file_id, ierr)
stop
end if
! 分配内存
allocate(data_set1(dims(1)))
! 读取数据集到数组
call h5dread_f(dataset_id, H5T_NATIVE_REAL, data_set1, dims, ierr)
if (ierr /= 0) then
print *, '无法读取数据集'
end if
! 关闭相关资源
call h5sclose_f(dataspace_id, ierr)
call h5dclose_f(dataset_id, ierr)
call h5fclose_f(file_id, ierr)
deallocate(data_set1)
end program read_hdf5_dataset
上述代码使用Fortran结合HDF5库,实现了打开HDF5文件并读取其中名为data_set1
的数据集到Fortran数组变量中。
- 库的使用:通过
use hdf5
引入HDF5库。 - 文件打开:使用
h5fopen_f
函数以只读方式打开HDF5文件。 - 数据集打开:利用
h5dopen_f
函数打开指定名称的数据集。 - 数据集空间与维度获取:通过
h5dget_space_f
获取数据集空间,h5sget_simple_extent_dims_f
获取数据集维度。 - 内存分配与数据读取:根据数据集维度分配数组内存,使用
h5dread_f
将数据读取到数组中。 - 资源关闭:最后关闭数据集、数据集空间和HDF5文件,并释放分配的数组内存。