-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.cpp
73 lines (52 loc) · 1.62 KB
/
file.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
#include "file.h"
File::File(const std::string filename) : filename(filename) {}
std::vector<std::string> File::fileLines(std::string filename) {
std::vector<std::string> file;
std::string temp;
std::ifstream infile(filename.c_str());
while ( std::getline(infile, temp) ) {
file.push_back(temp);
}
infile.close();
return file;
}
void File::addLine(std::string content) {
std::ofstream outfile;
outfile.open(filename, std::ios_base::app);
outfile << content << "\n";
outfile.close();
}
void File::deleteLine(int lineNumber) {
std::vector<std::string> file = fileLines(filename);
file.erase( file.begin() + lineNumber );
std::ofstream out("temp.cache", std::ios::out | std::ios::trunc);
for ( std::vector<std::string>::const_iterator i = file.begin(); i != file.end(); ++i) {
if ( *i != "" ) {
out << *i << std::endl;
}
}
out.close();
std::remove(filename.c_str());
std::rename("temp.cache", filename.c_str());
}
void File::writeLines() {
std::vector<std::string> file = fileLines(filename);
int j = 1;
for ( std::vector<std::string>::const_iterator i = file.begin(); i != file.end(); ++i) {
std::cout << j << ". " << *i << std::endl;
j++;
}
}
void File::editLine(int lineNumber, std::string content) {
std::vector<std::string> file = fileLines(filename);
std::ofstream out("temp.cache", std::ios::out | std::ios::trunc);
file.at(lineNumber) = content;
for ( std::vector<std::string>::const_iterator i = file.begin(); i != file.end(); ++i) {
if ( *i != "" ) {
out << *i << std::endl;
}
}
out.close();
std::remove(filename.c_str());
std::rename("temp.cache", filename.c_str());
}