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;
}
                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();
}
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With