-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCSVHandler.h
111 lines (96 loc) · 2.92 KB
/
CSVHandler.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
class CSVHandler {
private:
std::string filename;
public:
CSVHandler(const std::string& filename) : filename(filename) {}
bool fileExists() {
std::ifstream file(filename);
return file.good();
}
void createFile() {
std::ofstream file(filename);
if (file) {
file << "IsCustom,Name,Latitude,Longitude\n";
}
file.close();
}
std::vector<std::vector<std::string>> readCSV() {
std::vector<std::vector<std::string>> data;
std::ifstream file(filename);
if (file) {
std::string line;
while (std::getline(file, line)) {
std::vector<std::string> row;
std::string cell;
std::stringstream lineStream(line);
while (std::getline(lineStream, cell, ',')) {
row.push_back(cell);
}
data.push_back(row);
}
}
file.close();
return data;
}
void writeCSV(const std::vector<std::vector<std::string>>& data) {
std::ofstream file(filename, std::ios::app);
if (file) {
for (const auto& row : data) {
for (size_t i = 0; i < row.size(); ++i) {
file << row[i];
if (i != row.size() - 1) {
file << ",";
}
}
file << "\n";
}
}
file.close();
}
void deleteRowByName(const std::string& name) {
std::vector<std::vector<std::string>> data = readCSV();
std::vector<std::vector<std::string>> newData;
for (const auto& row : data) {
if (row.size() > 1 && row[1] != name) {
newData.push_back(row);
}
}
std::ofstream file(filename);
if (file) {
for (const auto& row : newData) {
for (size_t i = 0; i < row.size(); ++i) {
file << row[i];
if (i != row.size() - 1) {
file << ",";
}
}
file << "\n";
}
}
file.close();
}
void removeRowFromCSV(int row) {
std::vector<std::vector<std::string>> data = readCSV();
if (row >= 0 && row < data.size()) {
data.erase(data.begin() + row);
std::ofstream file(filename);
if (file) {
for (const auto& row : data) {
for (size_t i = 0; i < row.size(); ++i) {
file << row[i];
if (i != row.size() - 1) {
file << ",";
}
}
file << "\n";
}
}
file.close();
}
}
};