Search code examples
copybytefopenfilestreamfwrite

How to properly copy an executable byte by byte


I have recently been trying to learn more about copying files via bytes, but I am having trouble. When checking the bytes from the original notepad.exe against notepad2.exe, even though the fread and frwite size is consistent across reading and writing I get different results.

typedef unsigned char BYTE;
FILE* file;
FILE* ofile;

file = fopen("notepad.exe", "rb");

fseek(file, 0, SEEK_END);
long fSize = ftell(file);
rewind(file);

BYTE* ret = new BYTE[fSize];

fread(ret, 1, fSize, file);

fclose(file);

ofile = fopen("notepad2.exe", "w");
fwrite(ret, 1, fSize, ofile);

fclose(ofile);

I may be under the wrong assumption it even works like this, I am fairly new to working with lower level manipulation of memory. Thanks ahead for the help guys.


Solution

  • Download a free hex editor and visually check both files' bytes there. That will make it easier to see where things you went wrong.

    Obviously you have some extra bytes (possibly many 00 values) but... is it at the front or the back of copied file bytes?

    • Check value of Fsize, and length of ret (check before fwrite),
      are both matching your expected amounts?

    • Instead of :ofile = fopen("notepad2.exe", "w");
      try setting as:
      ofile = fopen("notepad2.exe", "wb");

    • Use a while or for loop to read each single byte from ret and write/append the same value to byte in disk file (notepad2.exe).