Hadi Rasekh
Hadi Rasekh

Reputation: 2740

read and write a binary file in c++ with fstream

I'm trying to write simple c++ code to read and write a file. The problem is my output file is smaller than the original file, and I'm stuck finding the cause. I have a image with 6.6 kb and my output image is about 6.4 kb

#include <iostream>
#include <fstream>

using namespace std;

ofstream myOutpue;
ifstream mySource;

int main()
{        

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

    char buffer;

    if (mySource.is_open())
    {
        while (!mySource.eof())
        {
            mySource >> buffer;            
            myOutpue << buffer;
        }
    }

    mySource.close();
    myOutpue.close();    

    return 1;
}

Upvotes: 4

Views: 10675

Answers (4)

RohitArora
RohitArora

Reputation: 16

Well, its just because of padding at the end of the image. eof of any file do not include the padded bytes added at the end of file. Try this take img1.jpg contains 20 space charecter at the end not visible here (uegfuyregwfyugwrerycgerfcg6ygerbucykgeugcrgfrgeyf ) and run your program (do not include parenthesis in the file, these are used to show the data content) you will see img2.jpg contains (uegfuyregwfyugwrerycgerfcg6ygerbucykgeugcrgfrgeyf)

So, its better option to read the file byte by byte using the filesize which you can get using stat, and run for loop till filesize. Hope this should resolve your problem you mentioned above

Upvotes: 0

FSFisGOOD
FSFisGOOD

Reputation: 183

There are 3 problems in your code:

1- You have not opened your output file in Binary.

2- Your code return "1", normally you should return "0", if something went wrong then return an error code.

3- You should use "manipulators" and make c++ not to avoid whitespaces, so in order to read from file instead of:

mySource >> buffer;

you should use:

mySource >> std:noskipws >> buffer;

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 477474

Why not just:

#include <fstream>

int main()
{
    std::ifstream mySource("im1.jpg", std::ios::binary);
    std::ofstream myOutpue("im2.jpg", std::ios::binary);
    myOutpue << mySource.rdbuf();
}

Or, less chattily:

int main()
{
    std::ofstream("im2.jpg", std::ios::binary)
        << std::ifstream("im1.jpg", std::ios::binary).rdbuf();
}

Upvotes: 5

Some programmer dude
Some programmer dude

Reputation: 409432

Two things: You forget to open the output in binary mode, and you can't use the input/output operator >> and << for binary data, except if you use the output operator to write the input-streams basic_streambuf (which you can get using rdbuf).

For input use read and for output use write.

Upvotes: 4

Related Questions