RLE算法变体C语言实现

 

  RLE算法:这种压缩编码是一种变长的编码,RLE根据文本不同的具体情况会有不同的压缩编码变体与之相适应,以产生更大的压缩比率。

 

  变体:重复次数+字符

  文本字符串:A A A B B B C C C C D D D D,编码后得到:3 A 3 B 4 C 4 D。

 

 

/*********************************************************************************************************** RLE.c 本演示程序提供了RLE的压缩和解压缩函数 **********************************************************************************************************/ #include #include #include /* 函数原型 */ int RLE_Compression(char * infile_name, char * outfile_name); int RLE_Decompression(char * infile_name, char * outfile_name); /* 主程序 */ void main(int argc, char *argv[]) { printf("RLE compression and decompression utility/n"); if (4 != argc) { printf("/nUsage : rle -c|d sourcefilename targetfilename/n"); exit(0); } if (! strcmp(argv[1], "-c")) { printf("/nCompress..."); RLE_Compression(argv[2], argv[3]); } else if (! strcmp(argv[1], "-d")) { printf("/nDecompress..."); RLE_Decompression(argv[2], argv[3]); } else printf("/nUnknow command./n"); } /************************************************************************** RLE_Decompression () 本函数用RLE算法对文件进行解压缩 **************************************************************************/ int RLE_Decompression(char * infile_name, char * outfile_name) { register int seq_len, i; char scratch_space[255],cur_char; FILE *infile, *outfile; if ((infile=fopen(infile_name, "rb")) == NULL) { strcpy(scratch_space, "Unable to open "); strcat(scratch_space, infile_name); puts(scratch_space); return 1; } if ((outfile=fopen(outfile_name, "wb")) == NULL) { strcpy(scratch_space, "Unable to open "); strcat(scratch_space, outfile_name); puts(scratch_space); return 1; } if ( feof(infile) ) { return 0; } while (!feof(infile)) { seq_len = (int)fgetc( infile ); cur_char = fgetc( infile ); for ( i = 0; i < seq_len; i++ ) { fputc( cur_char, outfile ); } } fclose(infile); fclose(outfile); return 0; } /************************************************************************** RLE_Compression () 本函数用RLE算法对文件进行压缩 **************************************************************************/ int RLE_Compression(char * infile_name, char * outfile_name) { register int seq_len; char scratch_space[255],cur_char, cur_seq; FILE *infile, *outfile; if ((infile=fopen(infile_name, "rb")) == NULL) { strcpy(scratch_space, "Unable to open "); strcat(scratch_space, infile_name); puts(scratch_space); return 1; } if ((outfile=fopen(outfile_name, "wb")) == NULL) { strcpy(scratch_space, "Unable to open "); strcat(scratch_space, outfile_name); puts(scratch_space); return 1; } if ( feof(infile) ) { return 0; } cur_char = fgetc(infile); cur_seq = cur_char; seq_len = 1; while (!feof(infile)) { cur_char = fgetc(infile); if ( cur_char == cur_seq ) { seq_len++; } else { fputc( seq_len, outfile ); fputc( cur_seq, outfile ); cur_seq = cur_char; seq_len = 1; } } fclose( infile ); fclose( outfile ); return 0; } 

 

  以上算法比较适合重复次数比较多的文件,否则不但不能达到压缩的效果,反而使文件倍增!!!

你可能感兴趣的:(数据结构,算法,c,语言,compression,null,file)