?? lzw.cpp
字號:
#pragma warning(disable: 4996)
#include "LZW.h"
#include <iostream>
using namespace std;
LZW::LZW(void)
{
}
LZW::~LZW(void)
{
}
int LZW::Search(const std::list <std::string>& T, const std::string& w)
{
list<string>::const_iterator it = T.begin();
int i = 0;
for(; it != T.end(); it++, i++)
{
if (*it == w)
return i;
}
return -1;
}
bool LZW::FindIndex(const std::list <std::string>& T, int i, string& w)
{
list<string>::const_iterator it = T.begin();
int j = 0;
for(; it != T.end(); it++, j++)
{
if (j == i)
{
w = *it;
return true;
}
}
return false;
}
void LZW::Compress(const std::string &sInput, const std::string &sOutput)
{
// open file
int fdIn = open(sInput.c_str(), O_RDONLY | O_BINARY);
if (fdIn == -1)
{
perror("Error at opening file");
return;
}
int fdOut = open(sOutput.c_str(), O_CREAT | O_TRUNC | O_WRONLY | O_BINARY, _S_IREAD | _S_IWRITE);
if (fdOut == -1)
{
perror("Error at creating/open file");
close(fdIn);
return;
}
//initialize
list <string> lT;
string w = "";
for(int j = 0; j < SYMBOL_MAX + 1; j++)
{
string aux = "";
aux += (SYMBOL_TYPE)j;
lT.push_back(aux);
}
//compress
int i = 0;
bool sourceHasSymbols = true;
SYMBOL_TYPE c;
string ww = "";
while (sourceHasSymbols)
{
if (read(fdIn, &c, sizeof(c)) <= 0)
sourceHasSymbols = false;
w = ww;
ww +=c;
if ((i = Search(lT, ww)) >= 0)
continue;
lT.push_back(ww);
i = Search(lT, w);
write(fdOut, &i, BYTES_LIMIT);
ww = c;
}
close(fdOut);
close(fdIn);
}
void LZW::Decompress(const std::string &sInput, const std::string &sOutput)
{
// open file
int fdIn = open(sInput.c_str(), O_RDONLY | O_BINARY);
if (fdIn == -1)
{
perror("Error at opening file");
return;
}
int fdOut = open(sOutput.c_str(), O_CREAT | O_TRUNC | O_WRONLY | O_BINARY, _S_IREAD | _S_IWRITE);
if (fdOut == -1)
{
perror("Error at creating/open file");
close(fdIn);
return;
}
//initialize
list <string> lT;
for(int j = 0; j < SYMBOL_MAX + 1; j++)
{
string aux = "";
aux += (SYMBOL_TYPE)j;
lT.push_back(aux);
}
int cW = 0;
int pW = 0;
bool sourceHasSymbols = true;
string sW;
string sP;
string aux;
SYMBOL_TYPE c;
read(fdIn, &cW, BYTES_LIMIT);
FindIndex(lT, cW, sW);
write(fdOut, sW.c_str(), sW.length());
while(sourceHasSymbols)
{
pW = cW;
if (read(fdIn, &cW, BYTES_LIMIT) <= 0)
{
sourceHasSymbols = false;
break;
}
FindIndex(lT, pW, sP);
aux = sP;
if (FindIndex(lT, cW, sW))
{
write(fdOut, sW.c_str(), sW.length());
c = sW[0];
aux += c;
}
else
{
c = sP[0];
aux += c;
write(fdOut, aux.c_str(), aux.length());
}
lT.push_back(aux);
}
close(fdIn);
close(fdOut);
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -