-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfileDB.cpp
More file actions
75 lines (65 loc) · 1.7 KB
/
fileDB.cpp
File metadata and controls
75 lines (65 loc) · 1.7 KB
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
#include "fileDB.h"
#include "iostream"
fileDB::fileDB() {
}
fileDB::~fileDB() {
if (m_file.is_open())
m_file.close();
}
int fileDB::open(std::string &filename) {
m_file.open(filename.c_str(), std::ios::in | std::ios::out);
if (!m_file) {
std::cerr << "Failed to open file\n";
return EXIT_FAILURE;
}
return 0;
}
string fileDB::read(string key) {
std::string row;
while (std::getline(m_file, row) && row[0] != '#') {
std::size_t pos = row.find(',');
std::string retrieved_key = row.substr(0, pos);
std::string retrieved_value = row.substr(pos+1);
if (retrieved_key == key)
return retrieved_value;
}
return "\0";
}
void fileDB::write(string key, string value) {
m_file.seekp(0, ios_base::end);
string fileEntry = key + "," + value + "\n";
m_file << fileEntry;
}
void fileDB::modify(string key, string value){
std::string row;
m_file.seekg(0, ios_base::beg);
while (std::getline(m_file, row)) {
if (row[0] != '#') {
std::size_t pos = row.find(',');
std::string retrieved_key = row.substr(0, pos);
std::string retrieved_value = row.substr(pos + 1);
if (retrieved_key == key) {
std::size_t currentPos = m_file.tellg();
std::size_t length = row.length() + 2;
m_file.seekp(currentPos - length);
m_file << '#';
break;
}
}
}
write(key, value);
}
void fileDB::remove(string key) {
std::string row;
while (std::getline(m_file, row) && row[0] != '#') {
std::size_t pos = row.find(',');
std::string retrieved_key = row.substr(0, pos);
std::string retrieved_value = row.substr(pos + 1);
if (retrieved_key == key) {
std::size_t currentPos = m_file.tellg();
std::size_t length = row.length();
m_file.seekp(currentPos - length);
m_file << "#";
}
}
}