How to write stl::string to HDF5 file in c++

2.5k views Asked by At

I am using HDF5 CPP library on windows platform. Basically I want write a compound datatype to H5 file which contain std::string.

This code is not giving any error but while writing to H5 file it writes garbage value...

Guys any hint is helpful...

Here is my code:-

#include <H5Cpp.h >
#include <vector>
#include <string>
#include <iostream>

using namespace std;
using namespace H5;


/**Compound datatype with STL Datatype*/
struct PostProcessingData
{
  std::string datatype;
};
void main()
{
    H5File file("ResultData.h5",H5F_ACC_TRUNC);
    Group grp(file.createGroup("PostProcessing"));

    PostProcessingData data;
    data.datatype = "stress:xx";

    // create spatial structure of data
    hsize_t len = 1;
    hsize_t dim[1] = {len};
    int rank = 1;
    DataSpace space(rank,dim); 

    // write required size char array
    hid_t strtype = H5Tcopy (H5T_C_S1);
    H5Tset_size (strtype, H5T_VARIABLE);

    //defining the datatype to pass HDF55
    H5::CompType mtype(sizeof(PostProcessingData));
    mtype.insertMember("Filename", HOFFSET(PostProcessingData, datatype), strtype);


    DataSet dataset =  grp.createDataSet("subc_id2",mtype,space);
    dataset.write(&data,mtype);
    space.close();
    mtype.close();
    dataset.close();
    grp.close();
    file.close();
    exit(0);
 }
1

There are 1 answers

1
Shamkumar Rajput On

I got the following workaround to store a string in HDF5:- I have to convert std:: string to char* pointer. HDF5 is very good with raw datatype.

#include "H5Cpp.h"
#include <vector>
#include <string>
#include <iostream>


using namespace std;
using namespace H5;


/**Compound datatype with STL Datatype*/
struct PostProcessingData
{
    char* datatype;
};

void main()
{
    H5File file("ResultData.h5",H5F_ACC_TRUNC);
    Group grp(file.createGroup("PostProcessing"));

    PostProcessingData data;
    std::string dt = "stress:xx";
    data.datatype = new char[dt.length()];
    data.datatype = const_cast<char*> (dt.data());

    // create spatial structure of data
    hsize_t len = 1;
    hsize_t dim[1] = {len};
    int rank = 1;
    DataSpace space(rank,dim); 

    // write required size char array
    hid_t strtype = H5Tcopy (H5T_C_S1);
    H5Tset_size (strtype, H5T_VARIABLE);

    //defining the datatype to pass HDF55
    H5::CompType mtype(sizeof(PostProcessingData));
    mtype.insertMember("Filename", HOFFSET(PostProcessingData, datatype), strtype);


    DataSet dataset =  grp.createDataSet("subc_id2",mtype,space);
    //While writing data to file it gives following error
    dataset.write(&data,mtype);
    space.close();
    mtype.close();
    dataset.close();
    grp.close();
    file.close();
    exit(0);

}

Here is file snapshot:- enter image description here