2017-05-30 30 views
0

讀取從HDF5 H5T_STRING所以我有一個包含一個數據集HDF5文件:如何用C

DATASET "updateDateTime" {DATATYPE H5T_STRING{ 
    STRSIZE 24; 
STRPAD H5T_STR_NULLPAD; 
CSET H5T_CSET_ASCII; 
CTYPE H5T_C_S1; 
} 
    DATASPACE SIMPLE{ (5)/(5) } 
    DATA{ 
    (0) : "2015-05-12\000\000\000\000\000\000\000\000\000\000\000\000\000\000", 
    (1) : "2015-05-13\000\000\000\000\000\000\000\000\000\000\000\000\000\000", 
    (2) : "2015-05-14\000\000\000\000\000\000\000\000\000\000\000\000\000\000", 
    (3) : "2015-05-15\000\000\000\000\000\000\000\000\000\000\000\000\000\000", 
    (4) : "2015-05-16\000\000\000\000\000\000\000\000\000\000\000\000\000\000" 
} 

我想讀用C此數據集,但我不能找到一個妥善的例子(我HDF5新手)。具體來說,我無法確定在閱讀時使用哪個H5T_NATIVE_ *。下面是代碼,我現在:

hid_t time_ds = H5Dopen(grp, "updateDateTime", H5P_DEFAULT); 
auto time_shape = get_dataset_shape(time_ds); 
char** time_str = (char **)malloc(time_shape[0] * sizeof(char *)); // TODO: memeory allocation correct?? 

status = H5Dread(time_ds, H5T_NATIVE_CHAR, H5S_ALL, H5S_ALL, H5P_DEFAULT, 
    time_str); 
/*do my stuff*/ 

free(time_str); 
status = H5Dclose(time_ds); 
+0

當你執行這段代碼,會發生什麼? – arboreal84

+0

那麼,time_str沒有填充數據後H5Dread()@ arboreal84 –

回答

0

挖掘到h5dump的源代碼後(該工具會與HDF5包),我終於得到它的工作。我不能說這是一個很好的解決方案,但希望這可以幫助遇到類似問題的其他人。

原來,原生類型可以通過此功能可以推測

hid_t h5tools_get_native_type(hid_t type) 
{ 
hid_t p_type; 
H5T_class_t type_class; 

type_class = H5Tget_class(type); 
if (type_class == H5T_BITFIELD) 
    p_type = H5Tcopy(type); 
else 
    p_type = H5Tget_native_type(type, H5T_DIR_DEFAULT); 

return(p_type); 
} 

然後,閱讀這樣的數據集:

type = H5Dget_type(dset); 
native_type = h5tools_get_native_type(type); 
auto shape = get_dataset_shape(dset); 
n_element = std::accumulate(shape.begin(), shape.end(), 1ull, std::multiplies<size_t>()); 
type_size = std::max(H5Tget_size(type), H5Tget_size(native_type)); 
size_t alloc_size = n_element * type_size; 
char * buf = BAT_NEW char[alloc_size]; 

status = H5Dread(dset, native_type, H5S_ALL, H5S_ALL, H5P_DEFAULT, buf); 

/*do my stuff*/ 

H5Tclose(native_type); 
H5Tclose(type); 
delete[] buf; 
0

嘗試

char* time_str = (char*) malloc(time_shape[0] * sizeof(char)); 

status = H5Dread(time_ds, H5T_NATIVE_CHAR, H5S_ALL, H5S_ALL, H5P_DEFAULT, &time_str); 
+0

謝謝,但這似乎並不奏效。 time_str仍然是空的 –

0

或者,您可以讀取(數據類型H5T_STRING的)數據集在C中使用HDFql這樣的:

hdfql_execute("SELECT FROM updateDateTime"); 
hdfql_cursor_first(NULL); 
printf("Dataset value is %s\n", hdfql_cursor_get_char(NULL)); 

如果數據集儲存一個以上的字符串(這似乎是你的情況下,通過查看h5dump上面貼的結果),你可以通過循環的結果集檢索這些:

hdfql_execute("SELECT FROM updateDateTime"); 
while(hdfql_cursor_next(NULL) == HDFQL_SUCCESS) 
{ 
    printf("Dataset value is %s\n", hdfql_cursor_get_char(NULL)); 
}