forked from Felipeasg/LFTracking
-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv.cpp
executable file
·124 lines (110 loc) · 2.96 KB
/
csv.cpp
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
113
114
115
116
117
118
119
120
121
122
123
124
#include "csv.h"
#include <QFile>
#include <QTextStream>
#include <QTextCodec>
#include <QRegExp>
#include <QDebug>
QList<QStringList> parse(const QString &string)
{
enum State {Normal, Quote} state = Normal;
QList<QStringList> data;
QStringList line;
QString value;
for (int i = 0; i < string.size(); i++) {
QChar current = string.at(i);
// Normal
if (state == Normal) {
// newline
if (current == '\n') {
// add value
line.append(value);
value.clear();
// add line
data.append(line);
line.clear();
}
// comma
else if (current == ',') {
// add line
line.append(value);
value.clear();
}
// double quote
else if (current == '"') {
state = Quote;
}
// character
else {
value += current;
}
}
// Quote
else if (state == Quote) {
// double quote
if (current == '"') {
int index = (i+1 < string.size()) ? i+1 : string.size();
QChar next = string.at(index);
if (next == '"') {
value += '"';
i++;
} else {
state = Normal;
}
}
// other
else {
value += current;
}
}
}
return data;
}
QString initString(const QString &string)
{
QString result = string;
result.replace("\r\n", "\n");
if (result.at(result.size()-1) != '\n') {
result += '\n';
}
return result;
}
QList<QStringList> CSV::parseFromString(const QString &string)
{
return parse(initString(string));
}
QList<QStringList> CSV::parseFromFile(const QString &filename, const QString &codec)
{
QString string;
QFile file(filename);
if (file.open(QIODevice::ReadOnly)) {
QTextStream in(&file);
in.setCodec(QTextCodec::codecForName(codec.toLatin1()));
string = in.readAll();
file.close();
}
return parse(initString(string));
}
bool CSV::write(const QList<QStringList> data, const QString &filename, const QString &codec)
{
QFile file(filename);
if (!file.open(QIODevice::WriteOnly)) {
return false;
}
QTextStream out(&file);
out.setCodec(codec.toLatin1());
foreach (const QStringList &line, data) {
QStringList output;
foreach (QString value, line) {
if (value.contains(QRegExp(",|\r\n"))) {
output << ("\"" + value + "\"");
} else if (value.contains("\"")) {
output << value.replace("\"", "”");
} else {
output << value;
}
}
out << output.join(";") << "\r\n";
}
file.close();
return true;
}