Hello everyone, i'm writing a C program that will read a text file and then encode the characters using huffman algorithm. So far i've read the files, built a tree, and now I'm building the strings to be used in encoding, Where i'm having problem is my BuildStrings function, instead of printing the 0s and 1s I appended to the array it outputs a series of 0s and 1s. Below is the BuildStrings function and the main function.
I'd appreciate your assistance.
Code:
/*This funtion will build strings to be used in Huffman encoding
It is recursive in nature and will traverse the tree while appending
0 to left paths and 1 to right paths. */
void BuildStrings(sTreenode *r)
{
//printf("I depeth is: %i\n",r->weight);
if ((r->LChild == NULL) && (r->RChild == NULL)) //found a leaf yet?
{strcpy(cStrings[(((int) r->data) & 0xff)],cPath); //if yes, copy the path to the string to the 2D array cStrings
iDepth--; //go back up a level
cPath[iDepth] = '\0';
return;
}
else //
{
iDepth++; //otherwise go down a level
cPath[iDepth] = '0'; //append 0 before taking the left path
BuildStrings(r->LChild); //calls the left child
cPath[iDepth] = '\0';
iDepth++; //
cPath[iDepth] = '1'; //append 1 before taking the right path
BuildStrings(r->RChild); //calls the right child
cPath[iDepth] = '\0';
}
iDepth--;
return; //return to the main function
}
/*Main program*/
int main()
{
iDepth = 0; // tells us what level of the tree we're currently in
for (int i=0; i<=255; i++) cPath[i]='\0'; //initializing cPath to nulls
for (int i=0; i<=255; i++) for(int j=0; j <= 255; j++)
cStrings[i][j]='\0'; //see above
float percent[255]; //array to hold the percentage frequency of each xter
total = CountChars(filename); //calls CountChars which counts the number of xters and their weight
printf("\nThe Total is: %d\n", total); //Prints the total no of characters read
printf("\n N Frequency Percentage\n");
printf(" --- --------- ----------\n");
for(int x= 0; x < 255;x++) //loop to print out all the characters
{
percent[x] = (iCharCount[x]* 100.0)/total ; //computes the frequency percentage of each character
if(iCharCount[x]){ //if xter is non-zero, print it
//printf("\n%3d %8d %8.3f",x,iCharCount[x],percent[x]); //prints the frequency of each array index
}
}
BuildTree(); //calls the funtion to build trees
BuildStrings(root);
//traverse(root);
printf("\n\nThe huffman code for the characters is as follows:\n");
for(int f= 0; f <= 255; f++)
{
printf("\n%3i %4i", f, cStrings[(((int) f) & 0xff)]);
}
return 0;
}