1、HDF5写char*类型或者string类型数据

一、描述:
创建一个.h5格式的文件,把char*或者string类型的数据写入到创建的文件中。

二、环境:
linux下,HDF5版本hdf5-1.10.1.tar.gz。

三、代码测试:

#include <iostream>
#include <vector>
#include <string.h>
#include "H5Fpublic.h"
#include "hdf5.h"
#include "hdf5_hl.h"
using namespace std;

int main(int argc, char *argv[])
{
    hid_t hdfId; // .h5文件的句柄
    const char *writeH5File = "testWriteh5String.h5"; // 在可执行目录下
    // 创建
    hdfId = H5Fcreate(writeH5File, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
    if(hdfId<0)
        return -1;

    // 写数据
    vector<char*> dataVector(10,"ISMILELI");
    int rank = 1; // 写入维度
    int width = strlen(dataVector.at(0));
    const char *childStr = "/ROOTCHILD";
    int length = dataVector.size(); // 写入一个char*的长度
    hid_t space,dataset;
    hid_t atype;
    herr_t  status;

    hsize_t fdim[] = {(hsize_t)length};

    space = H5Screate_simple(rank,fdim,NULL);
    if(space<0)
        return -1;
    atype= H5Tcopy(H5T_C_S1);
    status=H5Tset_size(atype,width);
    if(status<0)
          return -1;
    dataset = H5Dcreate1(hdfId,childStr,atype,space,H5P_DEFAULT);
    if(dataset<0)
          return -1;
    string tempStr = "";
    for(int i=0; i<length; i++)
        tempStr+=dataVector.at(i);
    status=H5Dwrite(dataset,atype,H5S_ALL,H5S_ALL,H5P_DEFAULT,tempStr.c_str());
    if(status<0)
          return -1;
    H5Sclose(space);
    H5Dclose(dataset);
    H5Tclose(atype);

    // 关闭
    herr_t herr;
    herr=H5Fclose(hdfId);
    if(herr<0)
        return -2;
    cout << "write success!" << endl;
    return 0;
}

四、运行结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/toby54king/article/details/80686952
今日推荐