2

Good morning. I created a huffman tree in c++ and it's perfectly working. If I take a simple string from a file and put that on my huffman tree.

This is the original text:

Ciao sono un esempio di algoritmo di huffman!

At the end of the compression with my Huffman Tree I will have an encoded string like this:

111101 010 1001 101 110 11111 101 0111 101 110 0001 0111 110 0010 11111 0010 1000 01100 010 101 110 0000 010 110 1001 00110 01101 101 111011 010 111010 1000 101 110 0000 010 110 00111 0001 11100 11100 1000 1001 0111 111100

I must write this string in a file that theoretically must to have less size of the original file, but obviously, the file has more size because the encoded string it's longer.

I tried to write the string in a binary file but it doesn't work. It has always greater size than the input one.

void IOFile :: WriteBinary(string str,string nome)
{
    ofstream file (nome.c_str(),ios::out|ios::binary);

    int len = str.size();

    char *stringa = new char[len];
    size_t length = str.copy(stringa, len);
    stringa[length] = '\0';
    file.write((char*)&stringa,len);
    file.close();
    delete stringa;
}


string IOFile :: ReadBinary(string percorso)
{
    ifstream file(percorso.c_str(),ios::in | ios::binary);
    file.seekg(0, ios::end);

    int sizeInBytes = file.tellg();
    file.seekg(0);

    char *buff = new char[sizeInBytes];
    if (file.is_open())
    {
        file.read((char*)&buff,sizeInBytes);
        file.close();
    }

    string stringa = buff;
    delete buff;
    return stringa;
}

This is the code in c++ that I wrote so far to write and read this Huffman file but, how could I explain, its behaviour is not correct?.

Can you help me for to create correctly Huffman file with smaller size than the original file?

Piotr Styczyński
  • 1,391
  • 10
  • 19
Matta
  • 21
  • 1

0 Answers0