How to write LZW compressed text to a file in C?

338 Views Asked by At

Hi i have done a simple LZW compressor in C but i couldn't find anything about how to write compressed values to a file.

For example i compressed a txt file which is "banana bandana" and the output code is :

98 97 110 257 97 32 256 110 100 259

How should i write this into a new file? I need to read it again with C and decompress it.

1

There are 1 best solutions below

6
Lrnt Gr On

I guess so, you should write your compressed data to another file, say 'banana.lzx'.

Here is how to write the compressed data to the file:

#include <stdlib.h>
int compressed_data[10] = {98, 97, 110, 257, 97, 32, 256, 110, 100, 259};
FILE * fp = fopen("banana.lzx", "w");
fwrite(compressed_data, sizeof(compressed_data[0]), sizeof(compressed_data), fp);
fclose(fp);

Here is how to read the compressed data from the file:

#include <stdlib.h>
int compressed_data[10] = {0};
FILE * fp = fopen("banana.lzx", "r");
fread(compressed_data, sizeof(compressed_data[0]), sizeof(compressed_data), fp);
fclose(fp);
/* compressed_data is retrieved, and can now be decompressed */

Remark: I don't know anything about LZW compression, but shouldn't the compressed data be a set of bytes? If so, why are you getting values above 255 (cf. 257, 256 and 259) ?