Molecular Dynamics Simulation  1.0
CSVWriter.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <array>
4 #include <filesystem>
5 #include <fstream>
6 #include <string>
7 #include <utility>
8 #include <variant>
9 #include <vector>
10 
11 #include "io/logger/Logger.h"
12 
19 template <typename T>
20 void write_csv_element(std::ofstream& file, const T& value);
21 
28 template <>
29 void write_csv_element<std::string>(std::ofstream& file, const std::string& value);
30 class CSVWriter {
31  public:
35  using serializable_types = std::variant<size_t, int, double, std::string>;
36 
45  CSVWriter(std::filesystem::path file_path, const std::vector<std::string>& headers, bool append, std::string separator = ";");
46 
54  explicit CSVWriter(std::filesystem::path file_path, bool append, std::string separator = ";");
55 
56  // Delete copy constructor and assignment operator
57  CSVWriter(const CSVWriter&) = delete;
59 
60  // Move constructor and assignment operator
61  CSVWriter(CSVWriter&&) noexcept;
62  CSVWriter& operator=(CSVWriter&&) noexcept;
63 
64  ~CSVWriter();
65 
71  void initialize(const std::vector<std::string>& headers);
72 
78  void writeRow(const std::vector<serializable_types>& row);
79 
80  private:
84  std::ofstream file;
85 
89  std::filesystem::path file_path;
90 
94  bool append;
95 
99  std::vector<std::string> headers;
100 
104  std::string separator;
105 };
void write_csv_element(std::ofstream &file, const T &value)
Writes a single element to the CSV file.
Definition: CSVWriter.cpp:8
std::string separator
The separator to use between values.
Definition: CSVWriter.h:104
CSVWriter & operator=(CSVWriter &)=delete
std::variant< size_t, int, double, std::string > serializable_types
The types that can be written to the CSV file.
Definition: CSVWriter.h:35
void initialize(const std::vector< std::string > &headers)
Initializes the CSV file and writes the header row.
Definition: CSVWriter.cpp:43
bool append
Whether to append to the CSV file or overwrite it.
Definition: CSVWriter.h:94
void writeRow(const std::vector< serializable_types > &row)
Writes a row to the CSV file.
Definition: CSVWriter.cpp:70
std::vector< std::string > headers
The headers of the CSV file.
Definition: CSVWriter.h:99
std::ofstream file
The file stream to write to.
Definition: CSVWriter.h:84
CSVWriter(const CSVWriter &)=delete
CSVWriter(std::filesystem::path file_path, const std::vector< std::string > &headers, bool append, std::string separator=";")
Creates a new CSVWriter instance.
Definition: CSVWriter.cpp:17
std::filesystem::path file_path
The path to the CSV file to write to.
Definition: CSVWriter.h:89