I am building a simple string compressor and expander.The logic i am using is as following. since all ASCII characters can fit in 8 bits if we limit the input characters to (from \32 to \128) they should fit in just 7 bits that means 1 bit saved.I am using following code.There are 4 functions 1st Compress file 2nd to expand file 3rd function creates binary value of character and assigns it to the array 4th function clears the array by assign all indexes 0.The compression works fine but decompression is not working rightly.The idea is to store eight characters with their 7 bit codes as 7 characters with 8 bits coed therefore the length of array is 7 * 8 = 56. for example the string ABCDEFGH gors into array as
{
0,1,0,0,0,0,1, //A is 65 after -32 its now 33 which is 100001
0,1,0,0,0,1,0, //B is 66 after -32 its now 34 which is 100010
0,1,0,0,0,1,1,
//and so on
0,1,0,1,0,0,0
}
this array will be read in the eight bits block and will be written in a file as 8 bit character for decompression reverse method is applied but for some reason its not working.I cant figure it out.
void compressFile(void)
{
FILE *raw;
FILE *new;
int bits[56];
char path[32];
int flag=1;
int i=0;
char c,ch;
printf("\nEnter the name of File.\n\t");
scanf("%s",path);
cln(bits);
new = fopen("compressed.txt","w+");
if (raw = fopen(path,"r+"))
{
while (flag)
{
for (i=6;i<56;i+=7)
{
c = fgetc(raw);
if (c == EOF)
{
flag = 0;
break;
}
//decreasing the character by 32 which will be added during decompression
c -= 32;
bin(c,&bits[i]);
}
for (i=7; i<56 ; i+= 8)
{
ch = 0;
ch += bits[i] * 128 ;
ch += bits[i - 1] * 64 ;
ch += bits[i - 2] * 32 ;
ch += bits[i - 3] * 16 ;
ch += bits[i - 4] * 8 ;
ch += bits[i - 5] * 4 ;
ch += bits[i - 6] * 2 ;
ch += bits[i - 7] ;
fputc(ch,new);
}
cln(bits);
}
fclose(raw);
fclose(new);
}
else
{
printf("\n\tUnexpected Error !!!\n");
getch();
}
}
void expandFile(void)
{
FILE *raw;
FILE *new;
int bits[56];
char path[32];
int flag=1;
int i=0;
char c,ch;
printf("\nEnter the name of File.\n\t");
scanf("%s",path);
cln(bits);
new = fopen("expanded.txt","w+");
if (raw = fopen(path,"r+"))
{
while (flag)
{
for (i=7;i<56;i+= 8)
{
c = fgetc(raw);
if (c == EOF)
{
flag = 0;
break;
}
bin(c,&bits[i]);
}
for (i=6; i<56 ; i+= 7)
{
ch = 0;
ch += bits[i] * 64 ;
ch += bits[i - 1] * 32 ;
ch += bits[i - 2] * 16 ;
ch += bits[i - 3] * 8 ;
ch += bits[i - 4] * 4 ;
ch += bits[i - 5] * 2 ;
ch += bits[i - 6] * 1 ;
//32 is added which was subtracted
ch += 32;
fputc(ch,new);
}
cln(bits);
}
fclose(raw);
fclose(new);
}
else
{
printf("\n\tUnexpected Error !!!\n");
getch();
}
}
void cln(int *p)
{
int i;
for (i=0;i<56;i++)
{
*(p + i) = 0;
}
}
void bin(char n,int *p)
{
int q = 0;
while (n > 1)
{
*(p - q) = n % 2;
n /= 2;
q ++;
}
*(p - q) = 1;
}