Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 313
Hadi Rasekh Avatar asked Dec 15 '22 23:12

Hadi Rasekh


2 Answers

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();
}
like image 158
Kerrek SB Avatar answered Dec 24 '22 02:12

Kerrek SB


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.

like image 35
Some programmer dude Avatar answered Dec 24 '22 01:12

Some programmer dude