【发布时间】:2014-06-18 09:45:10
【问题描述】:
我有一个问题,当我在一个 41 kb 的文件上使用它时,它会被压缩(尽管因为它使用运行长度编码,它似乎总是使文件大小加倍)并正确解压缩。但是,当我尝试在一个 16,173 kb 的文件上使用它并解压缩它时,它没有打开,文件大小为 16,171 kb ......所以它解压缩了它,但它没有恢复到原来的形式.. ..有些事情搞砸了....让我感到困惑,我似乎无法弄清楚我做错了什么....
使用的方法是游程编码,它将每个字节替换为一个计数后跟字节。
之前:
46 6F 6F 20 62 61 72 21 21 21 20 20 20 20 20
之后:
01 46 02 6F 01 20 01 62 01 61 01 72 03 21 05 20
这是我的代码:
void compress_file(FILE *fp_in, FILE *fp_out)
{
int count, ch, ch2;
ch = getc(fp_in);
for (count = 0; ch2 != EOF; count = 0) {
// if next byte is the same increase count and test again
do {
count++; // set binary count
ch2 = getc(fp_in); // set next variable for comparison
} while (ch2 != EOF && ch2 == ch);
// write bytes into new file
putc(count, fp_out);
putc(ch, fp_out);
ch = ch2;
}
fclose(fp_in);
fclose(fp_out);
fprintf(stderr, "File Compressed\n");
}
void uncompress_file(FILE *fp_in, FILE *fp_out)
{
int count, ch, ch2;
for (count = 0; ch2 != EOF; count = 0) {
ch = getc(fp_in); // grab first byte
ch2 = getc(fp_in); // grab second byte
// write the bytes
do {
putc(ch2, fp_out);
count++;
} while (count < ch);
}
fclose(fp_in);
fclose(fp_out);
fprintf(stderr, "File Decompressed\n");
}
【问题讨论】:
-
您的
for循环测试ch2 != EOF,但ch2尚未初始化,导致未定义的行为。 -
除了未初始化的数据,all 文件是否以 binary 模式打开?另外,打印
count在压缩循环的每次迭代中,ch的值在扩展外循环的每次迭代中再次出现。如果它们不一样,你就发现了你的问题。 -
运行长度编码仅在相同字节(或字或双字)值的较长序列可以缩短为计数和值时才有用。 RLE 处理每个字节没有意义。
-
是的,我用二进制打开了两个文件,并在十六进制编辑器中打开了两个文件,一切似乎都检查过了,我想@mfro 搞定了,让我看看我能不能修复它
-
感谢@user694733,从裂缝中溜走了
标签: c binary run-length-encoding