-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.cpp
47 lines (41 loc) · 1.17 KB
/
storage.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
#include "storage.h"
#include <fstream>
#include <sstream>
#include <unordered_map>
const std::string FILENAME = "passwords.txt";
void Storage::savePassword(const std::string &username, const std::string &password) {
std::unordered_map<std::string, std::string> data;
// Load existing data
std::ifstream infile(FILENAME);
std::string line;
while (std::getline(infile, line)) {
std::istringstream iss(line);
std::string u, p;
if (iss >> u >> p) {
data[u] = p;
}
}
infile.close();
// Add new data
data[username] = password;
// Save all data
std::ofstream outfile(FILENAME);
for (const auto &pair : data) {
outfile << pair.first << " " << pair.second << "\n";
}
outfile.close();
}
std::string Storage::loadPassword(const std::string &username) {
std::ifstream infile(FILENAME);
std::string line;
while (std::getline(infile, line)) {
std::istringstream iss(line);
std::string u, p;
if (iss >> u >> p) {
if (u == username) {
return p;
}
}
}
return "";
}