Thanks to extreme help and work, the compression is done.
Template used for dictionary was a list.
Here is compress code: This code is credited to Rui Wang
Code:
class compress
{
private:
ifstream sourceFile;
ofstream compressedFile;
list<string> table;
list<string>::iterator table_string;
void initialize()
{
string c;
for (int i=-128; i<128; i++)
{
c = (char)i;
table.push_back(c);
}
}
int searchTable(string str)
{
int pos = 0;
bool strFouned = false;
table_string = table.begin();
while (table_string != table.end())
{
if (str == *table_string)
{
strFouned = true;
break;
}
table_string ++;
pos++;
}
if (strFouned)
{
return pos;
}
else
{
return -1;
}
}
void writeCode(int code)
{
int val;
val = code/255;
compressedFile.put((char)val);
val = code%255;
compressedFile.put((char)val);
}
public:
compress(char *inputFile, char *outputFile)
{
sourceFile.open(inputFile, ios::binary);
if (!sourceFile)
{
cout << "File could not be opened!" << endl;
}
compressedFile.open(outputFile, ios::binary);
initialize();
}
~compress()
{
if (sourceFile)
{
sourceFile.close();
compressedFile.close();
}
}
void doCompress()
{
string buffer, tempString, c;
int pos;
buffer = sourceFile.get();
c = sourceFile.get();
while (!sourceFile.eof())
{
tempString = buffer + c;
pos = searchTable(tempString);
if (pos == -1)
{
pos = searchTable(buffer);
writeCode(pos);
table.push_back(tempString);
buffer = c;
}
else
{
buffer = tempString;
}
c = sourceFile.get();
}
pos = searchTable(buffer);
if (pos == -1)
{
pos = table.size();
}
writeCode(pos);
}
};
usage in main
compress *Compress = new compress(argv[2],argv[3]);
Compress->doCompress();
delete Compress;