-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsdb.cpp
146 lines (132 loc) · 2.26 KB
/
sdb.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#include <iostream>
#include <fstream>
#include <map>
#include <vector>
using namespace std;
map<string, string> data;
vector<string> keys;
int counter = 0;
void init()
{
ifstream reader;
reader.open("data");
if(reader.is_open())
{
while( !reader.eof() )
{
string key;
string value;
if( reader >> key )
keys.push_back(key);
if( reader >> value )
data[key] = value;
}
counter = keys.size();
reader.close();
}
else
{
ofstream maker;
maker.open("data");
maker.close();
}
}
void save()
{
fstream writer;
writer.open("data", ios::app | ios::out);
for( int i = counter; i < keys.size(); i++)
{
writer << keys[i] << " " << data[keys[i]] << endl;
}
writer.close();
}
void set(string key, string value)
{
data[key] = value;
if( count(keys.begin(), keys.end(), key) == 0 )
keys.push_back(key);
cout << "<" << key << "," << value <<">" " was added.\n";
}
string get(string key)
{
if( data.count(key) > 0 )
{
return data[key];
}
else
return "Key not found.";
}
void deline(string key)
{
string line;
ifstream in("data");
ofstream out("temp");
while( getline(in, line) )
{
if(line.compare(0,key.length(), key) != 0)
{
out << line << endl;
}
}
in.close();
out.close();
remove("data");
rename("temp","data");
}
void del(string key)
{
if( data.count(key) > 0 )
{
cout << "<" << key << "," << data[key] <<">" " was deleted.\n";
data.erase(key);
keys.erase(remove(keys.begin(), keys.end(), key), keys.end());
deline(key);
}
else
cout << "Key does not exist.\n";
}
int main()
{
init();
bool c = 1;
while(c)
{
string command;
cin >> command;
if( command == "set")
{
string key;
string value;
cin >> key;
cin >> value;
set(key, value);
}
else if( command == "get")
{
string key;
cin >> key;
cout << get(key) << endl;
}
else if( command == "delete")
{
string key;
cin >> key;
del(key);
}
else if( command == "exit")
{
c = 0;
}
else
{
cout << "Usage:\n";
cout << "\tset key value to add or edit an entry\n";
cout << "\tget key to retrieve an entry\n";
cout << "\tdelete key to delete an entry\n";
cout << "\texit to quit the program\n";
}
}
save();
return 0;
}