-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCsvFile.cpp
105 lines (97 loc) · 2.8 KB
/
CsvFile.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
#include <string>
#include <utility>
#include <vector>
#include <fstream>
#include "CsvFile.h"
CsvFile::CsvFile(std::string path) {
_strPath = std::move(path);
}
std::vector<std::vector<std::string>> CsvFile::read(int startLine, int endLine, char sep) const {
std::ifstream ifsFile(_strPath);
if (!ifsFile.is_open()) {
throw std::runtime_error("Cannot open file!");
}
std::vector<std::vector<std::string>> vtResult;
std::string strLine;
while (std::getline(ifsFile, strLine)) {
std::vector<std::string> vtRow;
std::string strCell;
if (strLine.empty()) {
continue;
}
for (char c: strLine) {
if (c == sep) {
if (strCell.empty()) {
continue;
}
vtRow.push_back(strCell);
strCell = "";
} else {
strCell += c;
}
}
vtRow.push_back(strCell);
vtResult.push_back(vtRow);
}
ifsFile.close();
if (endLine == -1) {
endLine = (int) vtResult.size();
}
if (startLine < 0 || endLine > vtResult.size()) {
throw std::runtime_error("Invalid line!");
}
vtResult.erase(vtResult.begin(), vtResult.begin() + startLine);
return vtResult;
}
bool CsvFile::write(const std::vector<std::vector<std::string>>& data, char sep) const {
std::ofstream ofsFile(_strPath, std::ios::out | std::ios::trunc);
if (!ofsFile.is_open()) {
return false;
}
for (const std::vector<std::string>& vtRow: data) {
for (int i = 0; i < vtRow.size(); ++i) {
ofsFile << vtRow[i];
if (i != vtRow.size() - 1) {
ofsFile << sep;
}
}
ofsFile << "\n";
}
ofsFile.close();
return true;
}
bool CsvFile::append(const std::vector<std::vector<std::string>>& data, char sep) const {
std::ofstream ofsFile(_strPath, std::ios::out | std::ios::app);
if (!ofsFile.is_open()) {
return false;
}
for (const std::vector<std::string>& vtRow: data) {
for (int i = 0; i < vtRow.size(); ++i) {
ofsFile << vtRow[i];
if (i != vtRow.size() - 1) {
ofsFile << sep;
}
}
ofsFile << "\n";
}
ofsFile.close();
return true;
}
void CsvFile::remove(int line) const {
std::vector<std::vector<std::string>> vtData = read(0, -1);
if (line < 0) {
line = (int) vtData.size() + line;
}
vtData.erase(vtData.begin() + line);
write(vtData);
}
bool CsvFile::rename(const std::string& newName) {
bool result = std::rename(_strPath.c_str(), newName.c_str()) == 0;
if (result) {
_strPath = newName;
}
return result;
}
bool CsvFile::del() {
return std::remove(_strPath.c_str()) == 0;
}