无法使用C中的Huffman树对文件进行编码

时间:2016-12-14 11:46:19

标签: c encoding compression bit-manipulation huffman-code

所以我有一个编码表和一个位文件Struct一次写一点。但是,当我尝试实际编码文件时,它通常会在打开时崩溃程序。当我尝试在Mac上打开它时会出现错误

  

无法打开文档“output.txt”。文本编码Unicode(UTF-8)不适用。

我将提供相关代码,希望您能帮助我发现问题。我一直在网上研究解决方案,并且一直在尝试不同的写作技巧,但没有任何作用。

以下是位文件的代码

struct bitfile
{
    FILE * file;
    unsigned char buffer;  //1 byte in size
    int index;  //tells you which byte your filling
};

struct bitfile * bitfile_open(char * name)
 {
     struct bitfile * result;
     result = malloc(sizeof(struct bitfile));
     result->file = fopen(name, "rw");
     result->buffer = 0;
     result->index=0;
     return result;
 }

void bitfile_write(struct bitfile * out, int bit){
    if (bit)
    {
        out->buffer |= (1<<out->index);
    }

    out->index++;
    if (out->index == 8)
    {
        fwrite (&out->buffer, 1, 1, out->file);
        out->index = 0;
        out->buffer = 0;
    }
}

然后这是程序从主要编码

的路线
int main(int argc, const char * argv[]){
    struct bitfile * output = bitfile_open("textOutput.txt");
    file = fopen(argv[1], "r");
    /**

    Other code which generate Huffman tree and gets encodings

    **/
    encode_file(file,output,encodings);
}

该函数迭代通过相关编码发送的文件到&#34; write_encoding&#34;功能

void encode_file(FILE * in, struct bitfile * out, char ** encodings){
    unsigned char c;
    c = fgetc(in);
    char * encoding;

    while(!feof(in))
    {
        encoding = encodings[c];
        write_encoding(out, encoding);
        c = fgetc(in);
    }

    const int EOT = 4;
    write_encoding(out, encodings[EOT]);
    Flush_Bits(out);
    fclose(in);
    bitfile_close(out);
}



void write_encoding(struct bitfile * out, char * encoding){
    assert(encoding != NULL);
    for(int i = 0; encoding[i] != '\0';i++)
    {
        int bit = encoding[i] - '0';
        bitfile_write(out,bit);
    }
}

0 个答案:

没有答案