RLE文件压缩程序
大一程序设计作业,写的比较简陋
运行方法是命令行参数
输入文件 -c/-d 输出文件
*注意 仅适用于ASCII码文件压缩解压
#include <iostream>
#include <cstring>
void compress(const char *file1,const char *file2){
FILE *fp1=fopen(file1,"rb");//打开文件
FILE *fp2=fopen(file2,"wb");
if(fp1==NULL){
printf("文件打开失败");
return;
}
int tempInt,flagInt,sameCount=0;
bool isFirst=true;
while((tempInt=fgetc(fp1))!=EOF){
if(isFirst){//如果是第一个字符直接存储并进行下一次循环
flagInt=tempInt;//存储标志字符
sameCount=1;//相同字符个数=1
isFirst=false;
continue;
}
if(tempInt==flagInt){//如果当前字符与标志字符相同则个数+1
sameCount++;
continue;
}else{
if(sameCount==1){//单一数据不需要压缩直接写入
fwrite(&flagInt,1,1,fp2);
}else{
sameCount+=192;//处理为压缩后的头部信息
fwrite(&sameCount,1,1,fp2);//存储头部信息
fwrite(&flagInt,1,1,fp2);//存储数据信息
}
flagInt=tempInt;//初始化
sameCount=1;
}
}
if(sameCount>1){//若最后的数据是多个重复数据则需要额外进行一次写入
sameCount+=192;
fwrite(&sameCount,1,1,fp2);
fwrite(&flagInt,1,1,fp2);
}
fclose(fp1);
fclose(fp2);
}
void decompress(const char *file1,const char *file2){
FILE *fp1=fopen(file1,"rb");//打开文件
FILE *fp2=fopen(file2,"wb");
if(fp1==NULL){
printf("文件打开失败");
return;
}
int tempInt;
while((tempInt=fgetc(fp1))!=EOF){
if(tempInt>192){//如果当前位大于192,说明是进行过压缩的数据
int dataInt=fgetc(fp1);//取得下一位的数据
for(int i=0;i<tempInt-192;i++)
fwrite(&dataInt,1,1,fp2);//循环进行写入
}else{
fwrite(&tempInt,1,1,fp2);//直接写入
}
}
fclose(fp1);
fclose(fp2);
};
int main(int argc,char** argv) {
if(argc!=4)
printf("参数错误");
else{
if(strcmp(argv[2],"-c")==0)
compress(argv[1],argv[3]);
else if(strcmp(argv[2],"-d")==0)
decompress(argv[1],argv[3]);
else
printf("参数错误");
}
return 0;
}