#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;
}