-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfiledata.cpp
53 lines (45 loc) · 1.03 KB
/
filedata.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
#include "filedata.h"
#include <cstring>
#include <iostream>
FileData::FileData(const std::string &name) :
filename(name),
buf(NULL),
size(0)
{
readFile();
}
FileData::~FileData() {
free(buf);
}
void FileData::padBuffer(int padding)
{
if (padding > 0) {
buf = (char*) realloc(buf, (size+padding)*sizeof(char));
if (buf == NULL) {
std::cerr << "Error: realloc() failed" << std::endl;
exit(EXIT_FAILURE);
}
memset(buf+size, 0, padding);
}
}
void FileData::readFile()
{
std::ifstream f(filename, std::ios::in | std::ios::binary);
if (!f) {
free(buf); buf = NULL;
return;
}
f.seekg(0, std::ios::end);
size = f.tellg();
if (size > maxsize || size < 0) {
free(buf); buf = NULL;
return;
}
f.seekg(0, std::ios::beg);
buf = (char*) malloc(size*sizeof(char));
if (buf == NULL) {
std::cerr << "Error: malloc() failed" << std::endl;
exit(EXIT_FAILURE);
}
f.read(buf, size);
}