C-运行长度编码不适用于大文件,适用于较小的文件

Joh*_*ner 0 c binary run-length-encoding

我有一个问题,当我使用这个在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");
    }
Run Code Online (Sandbox Code Playgroud)

mfr*_*fro 6

您错过了检查char溢出的运行长度计数,因此如果您的文件中依次包含超过255个相同的字符,则会出错.