-
Notifications
You must be signed in to change notification settings - Fork 6
/
BinaryFile.cpp
117 lines (89 loc) · 2.31 KB
/
BinaryFile.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
/*
* BinaryFile.cpp
*
* Created on: Jul 3, 2015
* Author: luc.martel
*/
#include "binaryfile.hpp"
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <string>
BinaryInFile::BinaryInFile(std::string filename)
: self(*this), mFileName(filename), mData((uint8_t *)0), mSize(0) {
Open();
}
BinaryInFile::BinaryInFile(std::vector<uint8_t> &data)
: self(*this), mFileName(""), mData((uint8_t *)0), mSize(0) {
mData = new uint8_t[data.size()];
mSize = data.size();
// Copy the data
// TODO: Optimize later - remove the copy
std::memcpy(mData, data.data(), mSize);
}
BinaryInFile::~BinaryInFile() {
if (mData) {
delete[] mData;
}
}
size_t BinaryInFile::GetSize() { return mSize; }
uint8_t *BinaryInFile::GetDataPointer() { return mData; }
uint8_t &BinaryInFile::operator[](uint32_t index) { return *(mData + index); }
void BinaryInFile::Save(std::string filename) {
std::ofstream os;
os.open(filename.c_str(), std::ios::binary);
os.write((char *)mData, mSize);
os.close();
}
void BinaryInFile::Open() {
if (mData) {
delete[] mData;
}
std::ifstream is;
is.open(mFileName.c_str(), std::ios::binary | std::ios::ate);
mSize = is.tellg();
is.seekg(0, std::ios::beg);
mData = new uint8_t[mSize];
is.read((char *)mData, mSize);
is.close();
}
BinaryOutFile::BinaryOutFile(std::string filename)
: mFileName(filename),
mData(0),
mSize(0),
mBufferSize(OUT_FILE_BUFFER_SIZE),
mPosition(0) {
// Allocate interbal buffer
mData = new uint8_t[OUT_FILE_BUFFER_SIZE];
// Open the file
mOS.open(mFileName.c_str(), std::ios::binary);
}
BinaryOutFile::~BinaryOutFile() {
if (mData) delete[] mData;
}
bool BinaryOutFile::Write(uint8_t *data, size_t size) {
bool rval = true;
uint32_t bytes_left_in_buffer = OUT_FILE_BUFFER_SIZE - mPosition;
if (size > bytes_left_in_buffer) {
// First, writes the buffer to file
FlushBuffer();
// Write direct to file
mOS.write((char *)data, size);
} else {
std::memcpy(mData + mPosition, data, size);
mPosition += size;
if (mPosition == mBufferSize) {
FlushBuffer();
}
}
return rval;
}
void BinaryOutFile::Close() {
FlushBuffer();
mPosition = 0;
mOS.close();
}
void BinaryOutFile::FlushBuffer() {
mOS.write((char *)mData, mPosition);
mPosition = 0;
}