Raymii.org
Quis custodiet ipsos custodes?Home | About | All pages | Cluster Status | RSS Feed
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
❗ This post is over five years old. It may no longer be up to date. Opinions may have changed.
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.
Recently I removed all Google Ads from this site due to their invasive tracking, as well as Google Analytics. Please, if you found this content useful, consider a small donation using any of the options below:
I'm developing an open source monitoring app called Leaf Node Monitoring, for windows, linux & android. Go check it out!
Consider sponsoring me on Github. It means the world to me if you show your appreciation and you'll help pay the server costs.
You can also sponsor me by getting a Digital Ocean VPS. With this referral link you'll get $200 credit for 60 days. Spend $25 after your credit expires and I'll get $25!
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