Advertisement
Anophoo

Huffman 05

Jun 26th, 2016
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1.  
  2. void createCharData(Map<ext_char, string> &data, Node* head, string result) {
  3. if (head -> one == NULL && head -> zero == NULL) {
  4. data.put(head -> character, result);
  5. }
  6. if (head -> one != NULL) {
  7. result = result + "1";
  8. createCharData(data, head -> one, result);
  9. }
  10. if (head -> zero != NULL) {
  11. result = result + "0";
  12. createCharData(data, head -> zero, result);
  13. }
  14. }
  15.  
  16.  
  17. /* Function: encodeFile
  18. * Usage: encodeFile(source, encodingTree, output);
  19. * --------------------------------------------------------
  20. * Encodes the given file using the encoding specified by the
  21. * given encoding tree, then writes the result one bit at a
  22. * time to the specified output file.
  23. *
  24. * This function can assume the following:
  25. *
  26. * - The encoding tree was constructed from the given file,
  27. * so every character appears somewhere in the encoding
  28. * tree.
  29. *
  30. * - The output file already has the encoding table written
  31. * to it, and the file cursor is at the end of the file.
  32. * This means that you should just start writing the bits
  33. * without seeking the file anywhere.
  34. */
  35. void encodeFile(istream& infile, Node* encodingTree, obstream& outfile) {
  36. Map<ext_char, string> data;
  37. string result = "";
  38. createCharData(data, encodingTree, result);
  39. char ch;
  40. while(true){
  41. if(infile.fail()) break;
  42. ch = infile.get();
  43. string str = data.get(ch);
  44. for (int i = 0; i < str.length(); i++) {
  45. if (str[i] == '0')
  46. outfile.writeBit(0);
  47. else
  48. outfile.writeBit(1);
  49. }
  50. }
  51. string tmp = data.get(PSEUDO_EOF);
  52. for (int i = 0; i < tmp.length(); i++) {
  53. if (tmp[i] == '0')
  54. outfile.writeBit(0);
  55. else
  56. outfile.writeBit(1);
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement