-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileImpl.cpp
117 lines (102 loc) · 2.82 KB
/
FileImpl.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
//
// Created by A7243 on 22.05.2023.
//
#include "FileImpl.h"
FileImpl::FileImpl(const std::string &fileName, bool readOnly) {
//check path
if(fileName.empty()) {
throw InvalidFileName(EC_INVALIDFILENAME_EMPTY);
} if (fileName.length() > 4096) {
throw InvalidFileName(EC_INVALIDFILENAME_LONG);
}
pFileName = fileName;
auto openFlags = std::ios::binary | std::ios::in;
if(!readOnly) {
openFlags |= std::ios::out;
}
fileStream.open(fileName.c_str(), openFlags);
fileStream.seekg(0);
checkFileError();
}
FileImpl::~FileImpl() {
fileStream.close();
}
void FileImpl::read(std::vector<char> &data, uint64_t length) {
fileStream.clear();
//limit length to end of file
const uint64_t size = sizeOf();
const uint64_t pos = fileStream.tellg();
length = std::min(length, size - pos);
data.resize(length);
fileStream.read(data.data(), length);
checkStreamError();
}
void FileImpl::write(std::vector<char> &data) {
fileStream.clear();
int64_t pos = fileStream.tellg();
fileStream.write(data.data(), data.size());
if(!fileStream.good()) {
fileStream.seekg(pos);
}
checkStreamError();
}
uint64_t FileImpl::sizeOf() {
fileStream.clear();
std::streampos end, current;
current = fileStream.tellg();
fileStream.seekg(0, std::ios::end);
end = fileStream.tellg();
fileStream.seekg(current, std::ios::beg);
checkFileError();
return end;
}
void FileImpl::close() {
if (fileStream.is_open()) {
fileStream.close();
} else {
throw FileException(EC_FILEEXCEPTION_CLOSED);
}
}
void FileImpl::setFilePointer(uint64_t filePointer) {
fileStream.clear();
if(filePointer <= sizeOf()) {
fileStream.seekg(filePointer);
checkFileError();
}else{
throw InvalidFilePointer();
}
}
uint64_t FileImpl::filePointer() {
fileStream.clear();
return fileStream.tellg();
}
std::string FileImpl::fileName() {
return pFileName;
}
//protected
void FileImpl::checkStreamError() {
if(!fileStream.good()) {
if(fileStream.eof()) {
throw IOException(EC_IOEXCEPTION_EOF);
}
if(fileStream.fail()) {
throw IOException(EC_IOEXCEPTION_FAIL);
}
if(fileStream.bad()) {
throw IOException(EC_IOEXCEPTION_BAD);
}
}
}
void FileImpl::checkFileError() {
if(!fileStream.good()) {
if(fileStream.eof()) {
throw FileException(EC_FILEEXCEPTION_EOF);
}
if(fileStream.fail()) {
throw FileException(EC_FILEEXCEPTION_FAIL);
}
if(fileStream.bad()) {
throw FileException(EC_FILEEXCEPTION_BAD);
}
}
}