2011-05-31 44 views
1

我目前在學習HDF5 API,我試圖在HDF5數據集(1列)中插入一組C++ std :: string。HDF5:在數據集中插入一組字符串

在下面的代碼片段中,我應該如何遍歷vector<string>並在正確的索引處插入每個字符串?

我該如何告訴HDF5我是否想使用固定長度的字符串或can-have-any-length std :: string?

vector<string> samples; 
(...) 
/* create HDF5 file */ 
hid_t  hdf5file= H5Fcreate(hdf5_filename, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); 
if(hdf5file==-1) 
    { 
    cerr << "Cannot create HDF5 file "<< hdf5_filename << endl; 
    return(EXIT_FAILURE); 
    } 
/* create a group in this file */ 
hid_t group = H5Gcreate2(hdf5file, "/MyGroup", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); 
if(group==-1) 
    { 
    cerr << "Cannot create HDF5 group "<< endl; 
    return(EXIT_FAILURE); 
    } 
/* create a dataspace for the samples array of one dimension */ 
hsize_t dim1=samples.size(); 
hid_t dataspace = H5Screate_simple(1, &dim1, NULL); 
if(dataspace==-1) 
    { 
    cerr << "Cannot create HDF5 dataspace "<< endl; 
    return(EXIT_FAILURE); 
    } 
/* create datatype for a string . How shoud I tell if i want a fixed-length string or a can-have-any-length string ?*/ 
hid_t datatype = H5Tcopy(H5T_C_S1); 
if(datatype==-1) 
    { 
    cerr << "Cannot create H5Tset_size "<< endl; 
    return(EXIT_FAILURE); 
    } 
int ret = H5Tset_size (datatype, H5T_VARIABLE); 
if(ret!=0) 
    { 
    cerr << "Cannot create H5Tset_size "<< endl; 
    return(EXIT_FAILURE); 
    } 
hid_t dataset = H5Dcreate2(group, "Samples", datatype, dataspace, 
     H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); 

for(vector<string>::size_type i=0;i< samples.size();++i) 
    { 
    /** here I'm puzzled, how should I insert the value of samples[i].c_str() at 
      the i-th index of the dataset ? */ 
    const char* sampleName= samples[i].c_str() ; 
    ???? 
     ???? 
    ???? 
    } 

/* close data set */ 
H5Dclose(dataset); 
/* close datatype */ 
H5Tclose(datatype); 
/* close the dataspace */ 
H5Sclose(dataspace); 


/* close the group */ 
H5Gclose(group); 

/* close hdf5 file */ 
H5Fclose(hdf5file); 
+0

的可能重複[如何最好寫出一個std :: vector 容器到HDF5數據集?](http://stackoverflow.com/questions/581209/how-to-best-write-out-a-stdvector-stdstring-container -to-A-HDF5-數據集) – Pierre 2011-06-04 14:36:36

回答

2

首先,使char*一個C數組的指針,以你的字符串:

const size_t n = samples.size(); 
char* data[n]; 
for (size_t i = 0; i < n; i++) 
{ 
    data[i] = samples[i].c_str(); 
} 

然後寫的一切一氣呵成:

H5Dwrite(dataset, datatype, dataspace, H5S_ALL, H5P_DEFAULT, data);