用Qt C++写一个csv格式转hdf5格式的代码
时间: 2023-06-24 21:06:10 浏览: 89
下面是一个简单的Qt C++代码,用于将CSV文件转换为HDF5格式。这个代码使用了HDF5 C++库(http://www.hdfgroup.org/HDF5/release/cpplus/),你需要先下载并安装该库。
```cpp
#include <QtCore/QCoreApplication>
#include <iostream>
#include <fstream>
#include <vector>
#include "H5Cpp.h"
using namespace H5;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// Check for the correct number of command line arguments
if (argc != 3)
{
std::cerr << "Usage: " << argv[0] << " input_file.csv output_file.h5" << std::endl;
return 1;
}
// Open the CSV file
std::ifstream infile(argv[1]);
// Read the CSV data into a vector of vectors
std::vector<std::vector<double>> data;
std::string line;
while (std::getline(infile, line))
{
std::vector<double> row;
std::stringstream ss(line);
std::string cell;
while (std::getline(ss, cell, ','))
{
row.push_back(std::stod(cell));
}
data.push_back(row);
}
// Get the dimensions of the data
hsize_t dims[2];
dims[0] = data.size();
dims[1] = data[0].size();
// Create a new HDF5 file
H5File file(argv[2], H5F_ACC_TRUNC);
// Create a new dataset in the file
DataSpace dataspace(2, dims);
DataSet dataset = file.createDataSet("/data", PredType::NATIVE_DOUBLE, dataspace);
// Write the data to the dataset
dataset.write(data.data(), PredType::NATIVE_DOUBLE);
return a.exec();
}
```
这个代码假设CSV文件中所有单元格都是数字,并且以逗号分隔。如果你的CSV文件不符合这个要求,你需要进行必要的修改。
阅读全文