Question

I am writing a compression program in C. It uses run length and Rice golomb encoding, applied at the bit leve. I have written the program and when I print out 1's and 0's to the screen, they are all correct. However I need to be able to take a file, compress it and output it to another file.

So what I have attempted to do is to store bits into a char, as I recieve them, and once I have added 8 bits, I print it to the new file. This is not working for me. Nothing is output into the file. I think the issue is that some of the bytes, obviously will not be corresponding to any ASCII character. Any suggestions please?

This is my code, to recieve a bit, add it to a char and then print the char to file once, it is 'filled'

void writeByte(char byte){
    FILE *comp;
    comp = fopen("compfile.txt" "wb");
    fprintf(comp,"%c", byte);
    putc(byte,comp);
    putchar(byte);
    printf("%c\n",byte);
}

void writeBit(int bit){
    if(ind >= 0){
        byte|=(bit<<ind);
        ind--
    }
    else{//if byte full
        writeByte(byte); //write a byte to file;
        reset();
        writeBit(bit);
    }
}
Was it helpful?

Solution 2

When you call fopen("compfile.txt", "wb"); the existing file (if any) gets truncated to zero length. To make this work, you need to open the file once at the beginning of the program, and then fclose the file at the end of the program.

Also, to view the file, you need to use a hex editor.

OTHER TIPS

fputc seems like the best option to use here since you're only writing one character at a time instead of a whole buffer (what fwrite does) and will save you the overhead of parsing a format string (in fprintf).

Replace fprintf(comp,"%c", byte); with fputc(byte, comp);

Other suggestions to your code:

  1. Don't fopen the same file every time you want to write a character to the file. You'll probably end up spending 2x more resources opening the file than actually writing to the file. Open once and pass the file descriptor in.
  2. You should probably name your byte variable differently. byte is a special keyword in C++. Even though your code is in C and you may never ever need to use it in C++ code, it may confuse some people reading your code.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top