Problem in writing the binary of a file after reading it into memory
Jun 26, 2010 at 5:02pm UTC
Following a guide in this site, I wrote a program to read in an exe's binary and then output it. But after I output the memory content of the file, some of the byte are duplicated, making the output file that suppose to be an exact copy of the file being read having a larger size. The following are my code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
// reading a complete binary file
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
ifstream::pos_type size;
char * memblock;
string filename="hjsplit.exe" ;//string filename="hjsplit.dat";
ifstream file(filename.c_str(), ios::in|ios::binary|ios::ate);
ofstream output("hjsplit.dat" );
int main () {
if (file.is_open())
{
size = file.tellg();
memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
for (int i=0;i<size;i++){output<<memblock[i];}
delete [] memblock;
}
else cout << "Unable to open file" <<endl;
system("pause" );
return 0;
}
However, not all file have byte duplicated, only certain files.
Jun 26, 2010 at 7:52pm UTC
Your ostream is not in binary mode.
BTW, you should create your file streams in the main block.
Hope this helps.
Last edited on Jun 26, 2010 at 7:52pm UTC
Jun 27, 2010 at 8:26am UTC
Ya, following your advice solve the problem, thanks.
Topic archived. No new replies allowed.