Unable to encode a file using Huffman tree in C

195 views Asked by At

So I have a table of encodings and a bit file Struct to write a bit at a time. However, when I attempt to actually encode a file it usually crashes the program upon opening. When I attempt to open it on a Mac it gives the error

The document “output.txt” could not be opened. Text encoding Unicode (UTF-8) isn’t applicable.

I will provide the relevant code and hope you can help me spot the problem. I have been researching online for a solution and have been trying different writing techniques but nothing works.

The following is the code for the bitfile

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

Then here is the route the program takes from the main to encode

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

This function iterates through the file sending in the relevant encoding to "write_encoding" function

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

There are 0 answers