📄 lzw2.cpp
字号:
#include"LZW2.h"
#define codes 16777216
#define ByteSize 8
#define excess 4
#define alpha 256
#define mask 15
unsigned char s[codes];
unsigned int size;
int LeftOver;
int status=0;
element ht[codes];
ifstream in;
ofstream out;
void SetFiles(int argc,char*argv[])
{
char OutputFile[50],InputFile[50];
if(argc>=2)strcpy(InputFile,argv[1]);
else
{
cout<<"Enter name of file to compress"<<endl;
cout<<"Omit the extension .zzz"<<endl;
cin>>InputFile;
}
if(strchr(InputFile,'.'))
{
cerr<<"File name has extension"<<endl;
exit(1);
}
if(in.fail())
{
cerr<<"Cannot open"<<InputFile<<endl;
exit(1);
}
strcpy(OutputFile,InputFile);
strcat(InputFile,".zzz");
in.open(InputFile,ios::binary);
strcat(OutputFile,".txt");
out.open(OutputFile,ios::binary);
}
void Output(unsigned long code)
{
size=-1;
while(code>=alpha)
{
s[++size]=ht[code].suffix;
code=ht[code].prefix;
}
s[++size]=(char)code;
for(int i=size;i>=0;i--)
out.put(s[i]);
}
bool GetCode(unsigned long& code)
{
unsigned char c,d,e;
in.get(c);
//cout<<c<<" ";
if(in.eof())return false;
in.get(d);
if(status)code=(LeftOver<<ByteSize*2)|(c<<ByteSize)|d;
else
{
in.get(e);
//cout<<d<<endl;
code=(c<<excess+ByteSize)|(d<<excess)|(e>>excess);
LeftOver=e&mask;
}
status=1-status;
return true;
}
void Decompress()
{
unsigned long used=alpha;
unsigned long pcode;
unsigned long ccode;
if(GetCode(pcode))
{
s[0]=(char)pcode;
out.put(s[0]);
size=0;
while(GetCode(ccode))
{
if(ccode<used)
{
Output(ccode);
if(used<codes)
{
ht[used].prefix=pcode;
ht[used++].suffix=s[size];
}
}
else
{
ht[used].prefix=pcode;
ht[used++].suffix=s[size];
Output(ccode);
}
pcode=ccode;
}
}
out.close();
in.close();
}
void main(int argc,char*argv[])
{
SetFiles(argc,argv);
Decompress();
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -