1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| /* * 从H5文件中读取矩阵数据,以column order存储数据 * * filename: H5文件名 * dataset_name: 数据集名 * buffer: 数据内存存储处,大小为 num_rows * num_cols * num_rows: 待读取的矩阵的行数 * num_cols: 待读取的矩阵的列数 * offset_x: 读取的数据在H5文件中的矩阵的x方向上的偏移 (第几行) * offset_y: 读取的数据在H5文件中的矩阵的y方向上的偏移 (第几列) * */ int read_direct_f(char *file_name, char *dataset_name, double *buffer, int num_rows, int num_cols, int offset_x, int offset_y) { int i;
hid_t file_id, dataset_id; hid_t dataspace_id, memspace_id; herr_t status;
hsize_t dims_mem[1];
hsize_t offset[2]; hsize_t count[2]; hsize_t stride[2]; hsize_t block[2]; hsize_t offset_mem[1]; hsize_t count_mem[1]; hsize_t stride_mem[1]; hsize_t block_mem[1];
// open the hdf5 file and the dataset file_id = H5Fopen(file_name, H5F_ACC_RDONLY, H5P_DEFAULT); dataset_id = H5Dopen2(file_id, dataset_name, H5P_DEFAULT);
// get file dataspace dataspace_id = H5Dget_space(dataset_id);
// create memory space dims_mem[0] = num_rows; // avoid numeric overflow dims_mem[0] = dims_mem[0] * num_cols; memspace_id = H5Screate_simple(1, dims_mem, NULL);
// specify size and shape of subset to read offset[0] = offset_x; offset[1] = offset_y; count[0] = 1; count[1] = num_cols; stride[0] = 1; stride[1] = 1; block[0] = 1; block[1] = 1; offset_mem[0] = 0; count_mem[0] = num_cols; stride_mem[0] = num_rows; block_mem[0] = 1;
for (i=0; i<num_rows; i++) { offset[0] = offset_x + i; offset_mem[0] = i;
// select subset from dataspace status = H5Sselect_hyperslab(dataspace_id, H5S_SELECT_SET, offset, stride, count, block); if (status < 0) { H5Eprint2(H5E_DEFAULT, NULL); return -1; }
status = H5Sselect_hyperslab(memspace_id, H5S_SELECT_SET, offset_mem, stride_mem, count_mem, block_mem); if (status < 0) { H5Eprint2(H5E_DEFAULT, NULL); return -1; }
// read data status = H5Dread(dataset_id, H5T_NATIVE_DOUBLE, memspace_id, dataspace_id, H5P_DEFAULT, buffer); if (status < 0) { H5Eprint2(H5E_DEFAULT, NULL); return -1; } }
// close the resources H5Sclose(memspace_id); H5Sclose(dataspace_id); H5Dclose(dataset_id); H5Fclose(file_id);
return 0; }
|