-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfileIO.cpp
96 lines (96 loc) · 2.01 KB
/
fileIO.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
#include "fileIO.h"
#include <string>
#include <fstream>
#define sentinel '*'
std::string fileIO::readFromFile(std::string filename)
{
std::ifstream in;
in.open(filename + ".txt");
std::string text;
getline(in, text);
in.close();
return text;
}
void fileIO::writeToFile(node* temp, std::string text, std::string filename)
{
std::ofstream out;
out.open(filename + "_compressed.txt");
out << text;
out.close();
out.open(filename + "_key.txt");
inorder(temp, out);
out << std::endl;
preorder(temp, out);
out.close();
}
node* fileIO::readBinaryTree(std::string filename)
{
std::ifstream in;
in.open(filename + "_key.txt");
std::string i, pre;
getline(in, i);
getline(in, pre);
node* head = buildTree(i, pre, 0, i.length() - 1);
in.close();
return head;
}
node* fileIO::buildTree(std::string in, std::string pre, int inStrt, int inEnd)
{
static int preIndex = 0;
if (inStrt > inEnd)
{
return NULL;
}
node* tNode = new node;
tNode->data = pre[preIndex++];
if (inStrt == inEnd)
{
return tNode;
}
int inIndex = search(in, inStrt, inEnd, tNode->data);
tNode->left = buildTree(in, pre, inStrt, inIndex - 1);
tNode->right = buildTree(in, pre, inIndex + 1, inEnd);
return tNode;
}
int fileIO::search(std::string arr, int strt, int end, char value)
{
for (int i = strt; i <= end; i++)
{
if (arr[i] == value)
{
return i;
}
}
}
void fileIO::inorder(node* temp, std::ofstream& out)
{
if (temp)
{
inorder(temp->left, out);
if (temp->data == sentinel)
{
out << char((int(temp->left->data) + int(temp->right->data) + temp->right->priority) % 256);
}
else
{
out << temp->data;
}
inorder(temp->right, out);
}
}
void fileIO::preorder(node* temp, std::ofstream& out)
{
if (temp)
{
if (temp->data == sentinel)
{
out << char(int(temp->left->data) + int(temp->right->data) + temp->right->priority);
}
else
{
out << temp->data;
}
preorder(temp->left, out);
preorder(temp->right, out);
}
}