0

I am trying to copy an exe file byte by byte. I compared the hex files of the 2 and they are quite different. It seems like some values are not getting loaded in..

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main(){

    ifstream fin("file.exe", ifstream::binary);
    vector<char> buffer(1, 0);


    ofstream newfile;
    newfile.open("newfile.exe", ios::binary);

    while (fin.read(buffer.data(), buffer.size())){
        streamsize s = fin.gcount();
        for (int i = 0; i < buffer.size(); i++){
            if (buffer[i] != EOF){
                newfile << buffer[i];
                cout << buffer[i] << endl;
            } else {
                break;
            }

        }
    }
}
Jlegend
  • 531
  • 1
  • 6
  • 19

2 Answers2

7

Why do you read into and write out of a vector with a single char? What is the purpose of s? Why do you attempt to compare against EOF with IOStreams? This code appears to be a bizarre mixture of C and C++, with the result being entirely broken!

Here's how I'd do it:

#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>

int main()
{
    std::ifstream fin ("file.exe",    std::ios::binary);
    std::ofstream fout("newfile.exe", std::ios::binary);

    std::copy(
       std::istream_iterator<char>(fin),
       std::istream_iterator<char>(),
       std::ostream_iterator<char>(fout)
    );
}

Or even just:

#include <iostream>
#include <fstream>

int main()
{
    std::ifstream fin ("file.exe",    std::ios::binary);
    std::ofstream fout("newfile.exe", std::ios::binary);

    fout << fin.rdbuf();
}

No muss, no fuss!

This works really well for streams in the general case, but, if all you want to do is perform a byte-for-byte file copy, you'd get your OS to do it for you. It can do it much faster than you can! For example, CopyFile on Windows.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

thank you for all the help. This is how I ended up getting the job done.

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

int main() {
    ifstream is("file.exe", ios::binary);
    ofstream fs("newfile.exe", ios::binary);
    if (is) {
        is.seekg(0, is.end);
        int length = is.tellg();
        is.seekg(0, is.beg);

        char * buffer = new char[length];

        is.read(buffer, length);
        is.close();

        for (int i = 0; i < length; i++) {
            fs << buffer[i];
        }

        delete[] buffer;
    }
}
Jlegend
  • 531
  • 1
  • 6
  • 19