-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbstream.h
69 lines (58 loc) · 1.55 KB
/
bstream.h
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
#ifndef BSTREAM_H_INCLUDED
#define BSTREAM_H_INCLUDED
#include <fstream>
using namespace std;
class Bstream {
private:
fstream fs;
unsigned char write_buffer;
unsigned char read_buffer;
int write_cur = 0;
int read_cur = 0;
public:
static const ios_base::openmode READ = ifstream::in | ifstream::binary;
static const ios_base::openmode WRITE = ifstream::out | ifstream::binary;
static const ios_base::openmode APPEND = ifstream::app | ifstream::binary;
static const ios_base::openmode READ_WRITE = ifstream::in | ifstream::out | ifstream::binary;
void open(string file_name, ios_base::openmode mode = READ_WRITE)
{ fs.open(file_name, mode); }
Bstream(string file_name, ios_base::openmode mode = READ_WRITE)
{ open(file_name, mode); }
Bstream() = default;
void write(bool binary);
bool read();
void close()
{
while (write_cur)
write(0);
read_cur = 0;
fs.close();
}
bool eof()
{ return fs.eof(); }
~Bstream()
{ close(); }
};
void Bstream::write(bool binary)
{
write_buffer >>= 1;
write_buffer |= binary << 7;
++write_cur;
if (write_cur == 8) {
fs.put(write_buffer);
write_cur = 0;
}
}
bool Bstream::read()
{
if (!read_cur)
read_buffer = fs.get();
bool binary = read_buffer & 1;
read_buffer >>= 1;
if (read_cur == 7)
read_cur = 0;
else
++read_cur;
return binary;
}
#endif // BSTREAM_H_INCLUDED