Tuesday 11 March 2014

How to make a C program which compress your text files or program files

Now you can compress your program or text files through this c program.This program gives an idea that how files are compressed.




 SOURCE CODE OUTPUT EXPLANATION DOWNLOAD


#include<stdio.h>
void main()
{
  FILE *fp1,*fp2;
  char sf[20],tf[20];
  int ch,select,count=0;
  clrscr();
  printf("\n1.) Compress File\t\t\tpress  1\n2.) Decompress File\t\t\tpress  2");
  scanf("%d",&select);
  printf("\nEnter the name of source file with extension ");
  scanf("%s",sf);
  printf("\nEnter the name of target file with extension ");
  scanf("%s",tf);
  fp1=fopen(sf,"r");
  fp2=fopen(tf,"w");
  if(fp1==NULL||fp2==NULL)
  {
    printf("Unable to open the file ");
    getch();exit(1);
  }
  switch(select)
  {
    case 1:
while((ch=getc(fp1))!=EOF)
{
 if(ch==' ')
 {
   while(ch==' ')
   {
     count++;
     ch=getc(fp1);
   }
   putc(count+127,fp2);
   count=0;
 }
 putc(ch,fp2);
}
printf("File has been compressed successfully");
break;
    case 2:
while((ch=getc(fp1))!=EOF)
{
 if(ch>127)
 {
   count=ch-127;
   while(count)
   {
     putc(' ',fp2);
     count--;
   }
   ch=getc(fp1);
 }
 putc(ch,fp2);
}
printf("File has being decompressed successfully");
break;
    default:
printf("Sorry Wrong choice");
break;
  }
  getch();
  fclose(fp1);
  fclose(fp2);
}

)
This program is not effective but it gives us an idea that how files are compressed. My program replace's all the spaces between words by a single graphic character for example if their are four spaces between two words than we will add 4 in 127 and store it in file .At the time of decompression we subtract 127 from ASCII value of that graphic character and than put that much spaces between words. In this way we will obtain our original file.
 Any questions regarding to program please write in comments.

No comments:

Post a Comment