File: history.cpp

package info (click to toggle)
newsbeuter 2.5-2%2Bdeb7u1
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 2,632 kB
  • sloc: cpp: 17,401; ruby: 1,796; xml: 350; makefile: 198; sh: 153; perl: 64
file content (69 lines) | stat: -rw-r--r-- 1,284 bytes parent folder | download | duplicates (4)
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
#include <fstream>
#include <history.h>

namespace newsbeuter {

history::history() : idx(0) { }

history::~history() { }

void history::add_line(const std::string& line) {
	/*
	 * When a line is added, we need to do so and
	 * reset the index so that the next prev/next
	 * operations start from the beginning again.
	 */
	if (line.length() > 0) {
		lines.insert(lines.begin(), line);
	}
	idx = 0;
}

std::string history::prev() {
	if (idx < lines.size()) {
		return lines[idx++];
	}
	if (lines.size() == 0) {
		return "";
	}
	return lines[idx-1];
}

std::string history::next() {
	if (idx > 0) {
		return lines[--idx];
	}
	return "";
}

void history::load_from_file(const std::string& file) {
	std::fstream f;
	f.open(file.c_str(), std::fstream::in);
	if (f.is_open()) {
		std::string line;
		do {
			getline(f, line);
			if (!f.eof() && line.length() > 0) {
				add_line(line);
			}
		} while (!f.eof());
	}
}

void history::save_to_file(const std::string& file, unsigned int limit) {
	std::fstream f;
	f.open(file.c_str(), std::fstream::out | std::fstream::trunc);
	if (f.is_open()) {
		if (limit > lines.size())
			limit = lines.size();
		if (limit > 0) {
			for (unsigned int i=limit-1;i>0;i--) {
				f << lines[i] << std::endl;
			}
			f << lines[0] << std::endl;
		}
	}
}


}