blob: d5bad673f4adf14fbbbc247625fb363b8637fc85 (
plain)
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
|
#include <cstdio>
#include <iterator>
#include "LocalFile.h"
#include "Exception.h"
LocalFile LocalFile::instance(protocol);
void LocalFile::open(const std::string url) {
std::string path = url;
if (path.starts_with(protocol))
path = path.substr(protocol.size());
this->file = new std::ifstream(path, std::ios::in);
if (this->file->fail() || !this->file->is_open())
throw Exception("cannot open file://%s\n", path.c_str());
}
void LocalFile::close() {
if (this->file == nullptr) return;
if (this->file->is_open())
this->file->close();
}
const std::string LocalFile::read() {
if (this->content != nullptr)
return *this->content;
if (this->file == nullptr)
throw Exception("FileStrategy read after destructor\n");
if (!this->file->is_open())
throw Exception("FileStrategy read after close\n");
this->content = new std::string(
std::istreambuf_iterator<char>(*this->file),
std::istreambuf_iterator<char>()
);
return *this->content;
}
LocalFile::~LocalFile() {
this->close();
if (this->file != nullptr) {
delete this->file;
this->file = nullptr;
}
if (this->content != nullptr) {
delete this->content;
this->content = nullptr;
}
}
LocalFile * LocalFile::clone() const {
return new LocalFile(this);
}
LocalFile::LocalFile(const LocalFile *) : FileStrategy() { }
|