2

I'm trying to write a c++ code to read file and code it as (1/0) binary, then get the original file from the (1/0) file. I have to reconstruct the original file from 1/0 binary file in some other computer, so 1/0 and how to reconstruct it is very important to me.

the cause is, my output file is smaller than the original file. for example if I have a 6.6 kb jpeg image the reconstructed file is about 6.4 kb.

#include <iostream>
#include <fstream>
#include <bitset>
using namespace std;

ofstream myOutput;
ifstream mySource;

int main()
{        

mySource.open("im1.jpg", ios_base::binary);
myOutput.open("im2.jpg", ios_base::binary);


unsigned char buffer;
unsigned char recBuffer;
unsigned int ascii;

if (mySource.is_open())
{
    while (!mySource.eof())
    {
    // code
    mySource >> buffer;
    ascii = static_cast<unsigned int>(buffer);
    cout<< bitset<8>(ascii) << endl;

    // reconstruction
    recBuffer = static_cast<char>(ascii);
    myOutput << recBuffer;
    }
}

mySource.close();
myOutput.close();

return 1;
}

3 Answers 3

5

The most naive solution I can think of might look like this:

#include <fstream>

int main()
{
    std::ifstream mySource("im1.jpg", std::ios::binary);
    std::ofstream myOutput("im2.jpg", std::ios::binary);

    for (char c; mySource.get(c); )
    {
        std::cout << static_cast<unsigned int>(static_cast<unsigned char>(c)) << "\n";
        myOutput.put(c);
    }
}

Strictly speaking you should probably check for write errors, too:

        if (!myOutput.put(c))
        { 
            std::cerr << "Write error!\n";
            break;
        }
2

You are ignoring whitespace in your input. Just change

while (!mySource.eof()) {
    mySource >> buffer;

with

while (mySource.get(buffer)) {

(and change unsigned char buffer for char buffer) and you should be ok...

1

">>" operation will ignore whitespaces by default, in order to avoid this ignorance! you should set "noskipws" falg, There are other flags too, for example "skipws" or "hex", These flags are called "manipulators" in c++ and you can read about them in here.

In this situation you should modify your code and add "noskipws":

while (!mySource.eof())
{
    // code
    mySource >> std:noskipws >>buffer;
    myOutput << recBuffer;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.