📄 lzcode.cpp
字号:
#include<stdio.h>
#include<map>
#include<iostream>
#include<fstream>
#include"MyWord.h"
#define SHORTMAX 32767
#define INTMIN (0-2147483648)
using namespace std;
typedef map <MyWord, long> MyDic;
void lzcode(ifstream& lzifs, ofstream& lzofs);
int main(int arg,char* argv[]){
if(arg < 2) printf("请输入压缩源文件。\n格式如下:\nLzCode 压缩源文件名\n");//检查参数正确性
else{
ifstream lzifs;
lzifs.open(argv[1],ios::in|ios::binary);
if(!lzifs) printf("压缩源文件不存在。\n");//检查源文件
else{
printf("Processing,please wait...\n");
ofstream lzofs;
string ofname;
ofname.assign(argv[1]);
ofname.append(".LZ");
lzofs.open(ofname.c_str(),ios::out|ios::binary);
lzcode(lzifs,lzofs);
lzifs.close();
lzofs.flush();
lzofs.close();
printf("ok!\n");
}
}
return 0;
}
void lzcode(ifstream& lzifs, ofstream& lzofs){
MyDic dic;
long no = 1;//全局,字典索引
char rd = 0;
MyWord * word = new MyWord();
long code = 0, itemp = 0;
short stemp = 0;
while(lzifs.get(rd)){//读取一个字节
word->index = code;//更改当前条目
word->ch = rd;
if(dic.find(*word) == dic.end()){//在字典中查询当前条目,查询不到则添加该条目
dic.insert(MyDic::value_type(*word,no));
if(code <= SHORTMAX) {stemp = (short)code; lzofs.write((char*)&stemp,2);}//能用short表示则写入short,不能则写入int,且为负数
else {itemp = (code|INTMIN); lzofs.write((char*)(((short*)&itemp)+1),2); lzofs.write((char*)&itemp,2);}
lzofs.put(rd);
//printf("%d,%c,",code,rd);
delete word;
word = new MyWord();//新建条目
no++;//全局索引加1
code = 0;
}
else{
code = dic[*word]; //查到条目则让code等于查询到的索引号
}
}
if(code != 0) {//将最后一次查询的索引写入
if(code <= SHORTMAX) {stemp = (short)code; lzofs.write((char*)&stemp,2);}
else {itemp = (code|INTMIN); lzofs.write((char*)(((short*)&itemp)+1),2); lzofs.write((char*)&itemp,2);}
}
if(!word) delete word;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -