C++不定参数实现写CSV文件

自己实现一个写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;

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值