-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun-length.cpp
More file actions
52 lines (44 loc) · 1.12 KB
/
run-length.cpp
File metadata and controls
52 lines (44 loc) · 1.12 KB
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
#include "run-length.h"
#include <cstdio>
#include <unistd.h>
#include "files.h"
#define BUF_SIZE 1024
void rle::compress(const std::string &file)
{
File input (file, true);
File output (file + ".rle", false);
char prev = input.read_char();
if (prev == EOF && prev == '\000') {
return;
}
char cnt = 1;
char current;
while ((current = input.read_char()) != EOF && current != '\000') {
if (current == prev)
cnt++;
else {
output.write_char(prev);
output.write_char(cnt);
cnt = 1;
prev = current;
}
}
output.write_char(prev);
output.write_char(cnt);
output.write_char(current); // Write EOF
output.flush();
}
void rle::decompress(const std::string &file)
{
File input (file, true);
File output (file.substr(0, file.size()-4), false);
char element;
char cnt;
while ((element = input.read_char()) != EOF && element != '\000') {
cnt = input.read_char();
for (int i = 0; i < (int)cnt; i++) {
output.write_char(element);
}
}
output.flush();
}