Search code examples
c++compressionreadfile

How to read any format of file to string for further compression with Huffman algorithm


How to read any format of file(doc, pdf, jpeg)? My version works only with txt so i am not able to properly decompress file.

My function for read from input file:

    std::string getDataFromFileToString(std::string &fName)
    {
    std::string s;
    std::ifstream fr(fName, std::ios_base::in | std::ios::binary);
    if (!fr.is_open())
    {
        std::cerr << "File \"" << fName << "\" does not exist\n";
        exit(EXIT_FAILURE);
    }
        char c;
        while(fr.get(c))
            s.push_back(c);
    fr.close();
    return s;
   }

Solution

  • If it only handles text files correctly, you probably need to open the files in binary mode:

    change

    std::ifstream fr(fName, std::ios_base::in);

    to

    std::ifstream fr(fName, std::ios_base::in | std::ios::binary);

    and make similar changes to your output file.