forked from CIS565-Fall-2020/Project2-Stream-Compaction
/
csvfile.hpp
112 lines (97 loc) · 2.14 KB
/
csvfile.hpp
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#pragma once
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
class csvfile;
inline static csvfile& endrow(csvfile& file);
inline static csvfile& flush(csvfile& file);
class csvfile
{
std::ofstream fs_;
bool is_first_;
const std::string separator_;
const std::string escape_seq_;
const std::string special_chars_;
public:
csvfile(const std::string filename, const std::string separator = ",")
: fs_()
, is_first_(true)
, separator_(separator)
, escape_seq_("\"")
, special_chars_("\"")
{
fs_.exceptions(std::ios::failbit | std::ios::badbit);
fs_.open(filename);
}
~csvfile()
{
flush();
fs_.close();
}
void flush()
{
fs_.flush();
}
void endrow()
{
fs_ << std::endl;
is_first_ = true;
}
csvfile& operator << (csvfile& (*val)(csvfile&))
{
return val(*this);
}
csvfile& operator << (const char* val)
{
return write(escape(val));
}
csvfile& operator << (const std::string& val)
{
return write(escape(val));
}
template<typename T>
csvfile& operator << (const T& val)
{
return write(val);
}
private:
template<typename T>
csvfile& write(const T& val)
{
if (!is_first_)
{
fs_ << separator_;
}
else
{
is_first_ = false;
}
fs_ << val;
return *this;
}
std::string escape(const std::string& val)
{
std::ostringstream result;
result << '"';
std::string::size_type to, from = 0u, len = val.length();
while (from < len &&
std::string::npos != (to = val.find_first_of(special_chars_, from)))
{
result << val.substr(from, to - from) << escape_seq_ << val[to];
from = to + 1;
}
result << val.substr(from) << '"';
return result.str();
}
};
inline static csvfile& endrow(csvfile& file)
{
file.endrow();
return file;
}
inline static csvfile& flush(csvfile& file)
{
file.flush();
return file;
}