-
Notifications
You must be signed in to change notification settings - Fork 0
/
CSVWriter.h
92 lines (72 loc) · 1.87 KB
/
CSVWriter.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#ifndef __CSVWRITER_H__
#define __CSVWRITER_H__
#include <fstream>
#include <sstream>
#include <vector>
namespace csv {
class Record {
private:
std::vector<std::string> items;
char seperator = ',';
public:
Record() = default;
Record(char seperator) : seperator(seperator) {}
Record(const std::vector<std::string>& record) : items(record) {}
Record(const std::vector<std::string>& record, char seperator)
: items(record), seperator(seperator) {}
~Record() = default;
template <typename T>
void put(const T& val) {
std::stringstream ss;
ss << val;
items.push_back(ss.str());
}
std::string toString() {
std::stringstream ss;
for (auto& item : items) {
if (&item == &*items.rbegin()) {
ss << item;
} else {
ss << item << seperator;
}
}
return ss.str();
}
bool empty() { return items.empty(); }
};
class CsvWriter {
private:
std::fstream file;
std::string filePath;
Record header;
std::vector<Record> records;
public:
CsvWriter(const std::string& filePath) : filePath(filePath) {
file.open(filePath, std::ios::out);
}
~CsvWriter() { close(); }
void setHeader(const Record& header) { this->header = header; }
void insertRecord(const Record& record) { records.push_back(record); }
bool isOpen() { return file.is_open(); }
void write() {
if (!header.empty()) {
file << header.toString() << std::endl;
}
for (auto& record : records) {
file << record.toString() << std::endl;
}
}
void write(Record& record) {
if (isOpen()) {
file.open(filePath, std::ios::out | std::ios::app);
}
file << record.toString() << std::endl;
}
void close() {
if (file.is_open()) {
file.close();
}
}
};
} /* csv */
#endif // __CSVWRITER_H__