/******************************************************* * compression.c * This program performs Huffman Compression on * the text in an input file and outputs the * compressed data to a specified output file * Useage: compression ********************************************************/ #include "compress.h" void main(int argc, char *argv[]) { FILE *input,*output; /*Pointers to input and output files*/ qtptr qfirst; /*Pointer to first element in queue*/ /*Check for proper number of arguments and exit if not*/ if(argc != 3) { printf("Usage: compress \n"); return; } /*Attempt to open designated input file in read-only mode*/ input = fopen(argv[1],"r"); /*Check to see that file has been successfully open and exit if not*/ if(!input) { printf("Error: Cannot open input file.\n"); printf("File should be in the same folder as compress.exe.\n"); return; } /*Attempt to open designated output file in write-only mode*/ output = fopen(argv[2],"w"); /*Check to see that file has been successfully open and exit if not*/ if(!output) { printf("Error: Cannot create output file.\n"); printf("Invalid name for output file.\n"); return; } /*Function called to create queue*/ qfirst = createQueue(input,output); /*Reset input to beginning of input file by closing and opening the file again*/ fclose(input); input = fopen(argv[1],"r"); /*Compress the data of the input file and output the result to the output file*/ encode(qfirst,input,output); /*Close both the input and output files*/ fclose(input); fclose(output); } /***************************************************************** * createQueue: This function obtains a FILE argument and * creates a priority queue based upon the contents of the file. * it then returns the pointer to the first element in the queue. ******************************************************************/ qtptr createQueue (FILE *input, FILE *output) { char ctemp; /*Temporary character*/ qtptr qfirst; /*Pointer to first element in priority queue*/ qfirst = q_mknode(fgetc(input)); while(TRUE) { /*Obtain next character and make sure it is not the end of the file*/ ctemp = fgetc(input); qfirst = q_addchar(qfirst,ctemp); /*Break AFTER EOF character has been stored in queue so that EOF is known for decoding*/ if(ctemp == EOF) { break; } } /*Store the priority queue into the file*/ q_filestore(qfirst,output); /*Return pointer to first element in queue*/ return qfirst; } /*encode: This function takes three arguments. The first argument is to the beginning of the priority queue, the second is a pointer to the input file, and the third is a pointer to the output file. This function calls two other tree functions that first create a tree and then encode the input file using Huffman compression*/ void encode(qtptr qfirst, FILE *input, FILE *output) { qtptr tptr; /*Pointer to root of tree*/ /*Create the tree*/ tptr = t_create(qfirst); /*Use the tree to encode the characters and store them into a file*/ t_charencode(tptr,input,output); }