-
Notifications
You must be signed in to change notification settings - Fork 0
Home
Jonathan Higgs edited this page Jul 16, 2022
·
3 revisions
A simple and fast c++20 csv library
Create a basic structure that represents the lines of data
struct my_data
{
int id;
std::string name;
std::string description;
};
Template specializations of the mappers fastcsv::to_csv<T>
and fastcsv::from_csv<T>
are required to map data to
csv files and vice-versa
Implementations of fastcsv::to_csv<T>
must inherit from fastcsv::csv_writer
which gives access to the helper
write()
method
template <>
struct fastcsv::to_csv<my_data> final : fastcsv::csv_writer
{
void operator()(const my_data & data)
{
write(data.id);
write(data.name);
write(data.description);
}
};
Implementations of fastcsv::from_csv<T>
must inherit from fastcsv::csv_reader
which gives access to the helper
read<T>()
methods
template <>
struct fastcsv::from_csv<my_data> final : fastcsv::csv_reader
{
[[nodiscard]] my_data operator()() const
{
return my_data{ read<int>), read<std::string>(), read<std::string>() };
}
};
using namespace std::string_view_literals;
template <>
struct fastcsv::csv_headers<my_data> final
{
[[nodiscard]] constexpr std::vector<std::string_view> operator() const noexcept
{
return std::vector{ "id"sv, "name"sv, "description"sv };
}
};
void example()
{
std::vector<my_data> data1 = fastcsv::load_csv<my_data>("path/to/data.csv");
std::vector<my_data> data2 = fastcsv::load_csv<my_data>("path/to/data-no-headers.csv", fastcsv::no_header);
std::string csv = fastcsv::write_csv(dat1);
std::string csvNoHeaders = fastcsv::write_csv(dat1, fastcsv::no_header);
auto data3 = fastcsv::read_csv<my_data>(csv);
auto data4 = fastcsv::read_csv<my_data>(csv, fastcsv::no_header);
fastcsv::save_csv("path/to/data.csv", data3);
fastcsv::save_csv("path/to/data-no-headers.csv", data3, fastcsv::no_header);
}