RLE文件压缩程序

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;
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值