0

I am writing a compression program with a huffman tree.

It generates a file filled with a bit of overhead de decompress and a bunch of random bits which are then split into pieces of 8 and turned into the char corresponding with those 8 bits. So essentially random chars. And then they are written into a file.

When reading this file two problems occur:

  1. The chars shown when I cout the random chars is different from the ones in the file.

  2. My loop that reads the file stops only a few lines in.

I'm using the following function to read the file:

void Convertor::HuffmanToFile(string outputLocation){
    string fileInfo, fileDataPiece;
    ifstream inputFile;
    ofstream outputFile;
    stringstream fileData;
    outputFile.open(outputLocation, ofstream::out | ofstream::trunc);
    inputFile.open(inputLocation);

    if (inputFile.fail()) {
        cerr << "Error opening text file" << endl;
        exit(1);
    }

    while (inputFile >> fileDataPiece){
        fileData << fileDataPiece;
    }

    inputFile.close();

    Decoder decoder(fileInfo,fileData.str());

    outputFile << decoder.decodeInfo();
    outputFile.close();
}

If anyone could hand me a clue as to where I should look into that would be great!

cpalinckx
  • 369
  • 2
  • 5

1 Answers1

0

Be careful when using operator>> from istream into string - it will skip over white space characters! My guess is that is causing the differences.

You are loading the whole file at once. Your way is unnecessary complicated. One good way to do it in C++ is described here: Read whole ASCII file into C++ std::string

Community
  • 1
  • 1
michalsrb
  • 4,202
  • 13
  • 29