File Compression

Code Id 4
Date Updated 3/7/2010
Title File Compression  
Write a squish program that reads a file, creates a new file whose contents are a compressed version of the original file,
and uses the standard function remove to remove the original file. The original file name is a command-line argument,
and the new file name is the original file name followed by .squish;for example, squish data.txt
will read data.txt, write data.txt.squish, and call remove("data.txt"). The compression procedure is to replace each th with Q;
for example, the thought is compressed into Qe Qought.Your program must exit nonzero (without removing the original file!)
if it has any trouble reading, writing, etc., or if the original file contains Q. 
Codes Snippet

int main(int argc,char **argv)
  char *x = 0;
  int xspace = 0;
  int xlen = 0;
  FILE *f;
  char *newfn;
  char c;

  if (!argv[1]) exit(100);

  f = fopen(argv[1],"r");
  if (!f) exit(111);

  while (fscanf(f,"%c",&c) == 1) {
    if (c == 'Q') exit(100);
    if (xlen == xspace) {
      xspace = xspace * 2 + 1;
      x = realloc(x,xspace * sizeof(int));
      if (!x) exit(111);
    if (xlen && (x[xlen - 1] == 't') && (c == 'h'))
      x[xlen - 1] = 'Q';
      x[xlen++] = c;

  if (ferror(f)) exit(111);

  newfn = malloc(strlen(argv[1]) + 8);
  if (!newfn) exit(111);


  f = fopen(newfn,"w");
  if (!f) exit(111);

  while (xlen-- > 0)
    if (fprintf(f,"%c",*x++) == -1) exit(111);

  if (fflush(f) == -1) exit(111);


Comments are closed.