自己实现一个写csv的类,方便使用,使用不定参数模板实现。
直接上代码,代码很简单,如果不设置csv头的话,就不校验每行数据的个数。
如果写入了头,那就校验每一行数据的个数。
头文件
#pragma once
#ifndef CSV_WRITER_INCLUDE_H_
#define CSV_WRITER_INCLUDE_H_
#include <fstream>
#include <vector>
#include <ios>
#include <memory>
class bugCheck
{
public:
static void assertion(const char *text);
};
#define my_dynamic_assert(cond, text) \
if (!(cond)) \
bugCheck::assertion(text); \
else \
(void)0
class CsvWriter
{
public:
explicit CsvWriter(const std::string &fileName);
~CsvWriter()
{
ofs_->close();
}
bool init();
void setPrecision(const int pre = 6)
{
ofs_->precision(pre);
}
void setIsFixed(bool is = true)
{
if (is)
{
*ofs_ << std::fixed;
}
}
bool writeHead(const std::vector<std::string> &headNames);
template <typename Arg>
void writeLineData(const Arg &arg)
{
if (columnCount != NO_HEAD_COUNT)
{
columnCount--;
my_dynamic_assert(columnCount == 0, "count of column data must be equal to count of column names\n");
}
*ofs_ << arg << "\n";
columnCount = INIT_COL_COUNT;
}
template <typename Arg1, typename... Args>
void writeLineData(const Arg1 &arg1, const Args &...args)
{
if (columnCount != NO_HEAD_COUNT)
{
columnCount--;
my_dynamic_assert(sizeof...(args) == columnCount, "count of column data must be equal to count of column names\n");
}
*ofs_ << arg1 << ",";
writeLineData(args...);
}
private:
const std::string fileName_;
std::shared_ptr<std::ofstream> ofs_;
int INIT_COL_COUNT = {-1};
const int NO_HEAD_COUNT = {-1};
int columnCount = {NO_HEAD_COUNT};
};
#endif
源文件
#include "CsvWriter.h"
void bugCheck::assertion(const char *text)
{
std::fputs(text, stderr);
std::abort();
}
CsvWriter::CsvWriter(const std::string &fileName)
: fileName_(fileName)
{
}
bool CsvWriter::init()
{
ofs_ = std::make_shared<std::ofstream>(fileName_);
if (!ofs_->is_open())
{
return false;
}
ofs_->precision(6);
*ofs_ << std::fixed;
return true;
}
bool CsvWriter::writeHead(const std::vector<std::string> &headNames)
{
if (headNames.empty())
{
return true;
}
INIT_COL_COUNT = static_cast<int>(headNames.size());
columnCount = INIT_COL_COUNT;
int end = headNames.size() - 1;
for (int i = 0; i < end; ++i)
{
*ofs_ << headNames[i] << ",";
}
*ofs_ << headNames[end] << "\n";
return true;
}
举个例子
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <time.h>
#include "CsvWriter.h"
int main(int argc, char** argv) {
CsvWriter writer("Samlpe.csv");
writer.init();
std::vector<std::string> headNames = {
"Id",
"Age",
"Name",
"Salary"
};
std::srand(time(nullptr));
writer.writeHead(headNames);
for (int i = 0; i < 1000; i++) {
writer.writeLineData(i, i+10000, "Jack", double(i) / rand());
}
return 0;
}