forked from ponchio/untrunc
-
Notifications
You must be signed in to change notification settings - Fork 3
/
file.cpp
115 lines (93 loc) · 2.18 KB
/
file.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
#include "file.h"
#include <string>
using namespace std;
static void reverse(int &input) {
int output;
char *a = ( char* )&input;
char *b = ( char* )&output;
b[0] = a[3];
b[1] = a[2];
b[2] = a[1];
b[3] = a[0];
input = output;
}
File::File(): file(NULL) {
}
File::~File() {
if(file)
fclose(file);
}
bool File::open(string filename) {
file = fopen(filename.c_str(), "r");
if(file == NULL) return false;
fseek(file, 0L, SEEK_END);
size = ftell(file);
fseek(file, 0L, SEEK_SET);
return true;
}
bool File::create(string filename) {
file = fopen(filename.c_str(), "wb");
if(file == NULL) return false;
return true;
}
void File::seek(long p) {
fseek(file, p, SEEK_SET);
}
long File::pos() {
return ftell(file);
}
bool File::atEnd() {
long pos = ftell(file);
return pos == size;
}
int File::readInt() {
int value;
int n = fread(&value, sizeof(int), 1, file);
if(n != 1)
throw string("Could not read atom length");
reverse(value);
return value;
}
int File::readInt64() {
int hi, low;
int n = fread(&hi, sizeof(int), 1, file);
if(n != 1)
throw string("Could not read atom length");
n = fread(&low, sizeof(int), 1, file);
if(n != 1)
throw string("Could not read atom length");
reverse(low);
return low;
}
void File::readChar(char *dest, int n) {
int len = fread(dest, sizeof(char), n, file);
if(len != n)
throw string("Could not read chars");
}
vector<unsigned char> File::read(long n) {
vector<unsigned char> dest(n);
long len = fread(&*dest.begin(), sizeof(unsigned char), n, file);
if(len != n)
throw string("Could not read at position");
return dest;
}
int File::writeInt(int n) {
reverse(n);
fwrite(&n, sizeof(int), 1, file);
return 4;
}
int File::writeInt64(int n) {
int hi = 0;
reverse(n);
fwrite(&hi, sizeof(int), 1, file);
fwrite(&n, sizeof(int), 1, file);
return 8;
}
int File::writeChar(char *source, int n) {
fwrite(source, 1, n, file);
return n;
}
int File::write(vector<unsigned char> &v) {
fwrite(&*v.begin(), 1, v.size(), file);
return v.size();
}