How to write data in a CSV file in C++

In this article we will discuss, how to create a class to write data to a CSV File.

What is a CSV File ?

A CSV file is a kind of flat file used to store the data. In this each row contains data separated by comma.
For example,

20,hi,99
3,4,5
a,b,c
3,4,1

Creating a CSVWriter Class to store Data to CSV File

Let’s create a class CSVWriter that provides API to store data to CSV File

/*
 * A class to create and write data in a csv file.
 */
class CSVWriter
{
	std::string fileName;
	std::string delimeter;
	int linesCount;

public:
	CSVWriter(std::string filename, std::string delm = ",") :
			fileName(filename), delimeter(delm), linesCount(0)
	{}
	/*
	 * Member function to store a range as comma seperated value
	 */
	template<typename T>
	void addDatainRow(T first, T last);
};

Its constructor accepts the filename as an argument. It also provide a template member function that accepts a range as an argument and store all of them in last row, separated by comma i.e.

/*
 * This Function accepts a range and appends all the elements in the range
 * to the last row, seperated by delimeter (Default is comma)
 */
template<typename T>
void CSVWriter::addDatainRow(T first, T last)
{
	std::fstream file;
	// Open the file in truncate mode if first line else in Append Mode
	file.open(fileName, std::ios::out | (linesCount ? std::ios::app : std::ios::trunc));

	// Iterate over the range and add each lement to file seperated by delimeter.
	for (; first != last; )
	{
		file << *first;
		if (++first != last)
			file << delimeter;
	}
	file << "\n";
	linesCount++;

	// Close the file
	file.close();
}

As this function expects a range, we can pass iterator of any container like vector/set or an array.

Let’s create an object of CSVWriter class i.e.

// Creating an object of CSVWriter
CSVWriter writer("example.csv");

Write a Vector of strings to CSV file using CSVWriter class

// Creating a vector of strings
std::vector<std::string> dataList_1 = { "20", "hi", "99" };

// Adding vector to CSV File
writer.addDatainRow(dataList_1.begin(), dataList_1.end());

Write a Set to CSV file using CSVWriter class

// Create a set of integers
std::set<int> dataList_2 = { 3, 4, 5};

// Adding Set to CSV File
writer.addDatainRow(dataList_2.begin(), dataList_2.end());

Write an Array to CSV file using CSVWriter class

// An array of int
int arr [] = {3,4,1};

// Wrote an elements in array to csv file.
writer.addDatainRow(arr , arr + sizeof(arr) / sizeof(int));

Check complete example as follows,

#include <iostream>
#include <fstream>
#include <vector>
#include <set>
#include <iterator>
#include <string>
#include <algorithm>

/*
 * A class to create and write data in a csv file.
 */
class CSVWriter
{
	std::string fileName;
	std::string delimeter;
	int linesCount;

public:
	CSVWriter(std::string filename, std::string delm = ",") :
			fileName(filename), delimeter(delm), linesCount(0)
	{}
	/*
	 * Member function to store a range as comma seperated value
	 */
	template<typename T>
	void addDatainRow(T first, T last);
};

/*
 * This Function accepts a range and appends all the elements in the range
 * to the last row, seperated by delimeter (Default is comma)
 */
template<typename T>
void CSVWriter::addDatainRow(T first, T last)
{
	std::fstream file;
	// Open the file in truncate mode if first line else in Append Mode
	file.open(fileName, std::ios::out | (linesCount ? std::ios::app : std::ios::trunc));

	// Iterate over the range and add each lement to file seperated by delimeter.
	for (; first != last; )
	{
		file << *first;
		if (++first != last)
			file << delimeter;
	}
	file << "\n";
	linesCount++;

	// Close the file
	file.close();
}
int main()
{
	// Creating an object of CSVWriter
	CSVWriter writer("example.csv");

	std::vector<std::string> dataList_1 = { "20", "hi", "99" };

	// Adding vector to CSV File
	writer.addDatainRow(dataList_1.begin(), dataList_1.end());

	// Create a set of integers
	std::set<int> dataList_2 = { 3, 4, 5};

	// Adding Set to CSV File
	writer.addDatainRow(dataList_2.begin(), dataList_2.end());

	std::string str = "abc";

	// Adding characters in a string in csv file.
	writer.addDatainRow(str.begin(), str.end());

	// An array of int
	int arr [] = {3,4,1};

	// Wrote an elements in array to csv file.
	writer.addDatainRow(arr , arr + sizeof(arr) / sizeof(int));

	return 0;
}

It generates a file example.csv with following contents,

20,hi,99
3,4,5
a,b,c
3,4,1

To compile the above code on Linux, use following command,

g++ –std=c++11 example.cpp

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top