Articles

C++ how to patch a file?

January 25, 2007 at 12:35:04
Specs: Windows XP, Intel

Hi

I've just started learning C++ and want to write a small application that writes the contents of a 64k BIN file into another exe file at a specific offset address.

Does anyone have any suggestions or source code to do this?

Any help & advice is much appreciated.

Thanks

Strutter


See More: C++ how to patch a file?

Report •


#1
January 25, 2007 at 16:55:33

This is as far as I have got but I don't know how to get the code to write the contents of demo1.bin to a specific offset in demo2.bin.

Any help please guys?


#include <vcl.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
#pragma hdrstop

-------------------

#pragma argsused
int main(int argc, char* argv[])
{
char buffer[1];
int i = 0;
ifstream inFile ("demo1.bin", ios::in | ios::binary);
ofstream outFile ("demo2.dra", ios::out | ios::binary);
while (!inFile.eof()){
inFile.read (buffer, 1);
outFile.write (buffer,1);
i++;
if (i < 65534){
i = 0;
}
}
inFile.close();
outFile.close();
cout << "demo2.bin patched" << endl;


Report •

#2
January 27, 2007 at 20:38:53

This code generates a file to be patched, generates a patch file, and runs the patch.

You should get the idea. If not, get back to me.

#include <iostream>
#include <fstream>
using namespace std;
void genFile();
void genPatchFile();
void genThePatch();
int main(int argc, char * argv[])
{
cout << "hi\n";
genFile();
genPatchFile();
genThePatch();
cout << "bye\n";
}
void genFile()
{
ofstream ofile("main.bin",ios::out|ios::binary);
unsigned char c = '\0';
for (int i = 0; i < 4096; i++)
{
ofile.put(c);
c += 1;
}
ofile.close();
}

void genPatchFile()
{
ofstream ofile("patch.bin",ios::out|ios::binary);
unsigned char c = 255;
for (int i = 0; i < 256; i++)
{
ofile.put(c);
}
ofile.close();
}
void genThePatch()
{
cout << "started patch gen\n";
ifstream inmain("main.bin",ios::in|ios::binary);
ifstream inpatch("patch.bin",ios::in|ios::binary);
ofstream patched("main.patched.bin",ios::out|ios::binary);
int patchStartOffset = 128 ; // A parameter, CHANGE ME!
char ioChar;
for (int i = 0; i < patchStartOffset; i++)
{
inmain.get(ioChar);
patched.put(ioChar);
}
int patchLen = 0;
while (inpatch.get(ioChar))
{
patched.put(ioChar);
patchLen++;
}
//
streampos mainPos = inmain.tellg();
mainPos += patchLen;
inmain.seekg(mainPos);
while (inmain.get(ioChar))
{
patched.put(ioChar);
}
patched.close(); inpatch.close(); inmain.close();
}


Report •

Related Solutions


Ask Question