Skip to main content

Raymii.org Logo (IEC resistor symbol) logo

Quis custodiet ipsos custodes?
Home | About | All pages | RSS Feed | Gopher

C++ create and write to a CSV file with a variadic template

Published: 17-06-2019 | Author: Remy van Elst | Text only version of this article


Table of Contents


In this snippet I'll show you a variadic template to write to a file. In line with my other experiments to get a better grasp at templates, this example improves on my earlier attempt by using a variadic template, thus allowing you to provide an infinite number of columns to the csv file of any type that has the overloaded << operator.

If you like this article, consider sponsoring me by trying out a Digital Ocean VPS. With this link you'll get $100 credit for 60 days). (referral link)

In the first example I wrote to a CSV file with a set amount of columns and types. After experimenting some more with templates and variadic templates, I tried to create this function again but with templates. A simple example, without any checking if a file already exists or is successfully opened. It would probably be better to pass the CSV data via a struct since most of the time the data format is going to be the same.

The code

#include <iostream>
#include <mutex>
#include <fstream>

std::mutex logMutex;

bool fileExists(std::string& fileName) {
    return static_cast<bool>(std::ifstream(fileName));
}

template <typename filename, typename Arg>
void writeFile(filename &fileName, Arg arg) {
    std::lock_guard<std::mutex> csvLock(logMutex);
    std::fstream file;
    file.open (fileName, std::ios::out | std::ios::app);
    if (file)
        file << arg;
}


template <typename filename, typename First, typename... Args>
void writeFile(filename &fileName, First first, Args... args) {
    writeFile(fileName, first);
    writeFile(fileName, args...);
}

int main() {
    std::string theFile = "a";
    if(!fileExists(theFile))
        writeFile(theFile, "\"header1\",", "\"header2\",", "\"header3\"", "\n");
    writeFile(theFile, "\"data1\",", "\"data2\",", "\"data3\"", "\n");
    writeFile(theFile, "\"second1\",", "\"second2\",", "\"second3\"", "\n");
    return 0;
}
Tags: c++ , cpp , csv , development , linux , python , snippets , software , templates , variadic