I am currently working on a little binary patcher. My current code works fine but I do want my code to be optimized (fast) and as clean as possible. Could you all please help me review this?
IDE: Delphi 7 and XE7
const
OriginalByte: array [0 .. 55] of Byte = ($64, $69, $6E, $67, $20, $6D, $65,
$20, $68, $69, $73, $00, $00, $00, $00, $27, $00, $00, $28, $00, $00, $00,
$21, $00, $00, $00, $63, $6F, $6D, $70, $75, $74, $65, $72, $2E, $00, $00,
$00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $27, $00, $00, $28,
$00, $00, $00, $00);
BytetoWrite: array [0 .. 55] of Byte = ($63, $68, $6F, $67, $20, $6D, $65,
$20, $68, $69, $73, $00, $00, $00, $00, $27, $00, $00, $28, $00, $00, $00,
$21, $00, $00, $00, $63, $6F, $6D, $70, $75, $74, $65, $72, $2E, $00, $00,
$00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $27, $00, $00, $28,
$00, $00, $00, $06);
function CompareByteArrays(FirstArray, SecondArray: array of Byte): Boolean;
var
Counter: Integer;
begin
Result := True;
if Length(FirstArray) <> Length(SecondArray) then
begin
Result := False;
Exit;
end;
for Counter := Low(FirstArray) to High(FirstArray) do
begin
if (FirstArray[Counter]) <> (SecondArray[Counter]) then
begin
Result := False;
Exit;
end
end;
end;
procedure DoMyPatch();
var
i: Integer;
FileName: string;
input: TFileStream;
FileByteArray, ExtractedByteArray: array of Byte;
begin
FileName := 'Cute1.res';
try
input := TFileStream.Create(FileName, fmOpenReadWrite);
except
on E: Exception do
begin
ShowMessage(E.Message);
Exit;
end
end;
input.Position := 0;
SetLength(FileByteArray, input.size);
input.Read(FileByteArray[0], Length(FileByteArray));
for i := Low(FileByteArray) to High(FileByteArray) do
begin
ExtractedByteArray := Copy(FileByteArray, i, Length(OriginalByte));
if CompareByteArrays(ExtractedByteArray, OriginalByte) = True then
begin
// Begin Patch
input.Free;
try
Win32Check(CopyFile(PChar(FileName), PChar(ChangeFileExt(FileName,
'.BAK')), False));
except
on E: Exception do
begin
ShowMessage(E.Message);
Exit;
end
end;
try
input := TFileStream.Create(FileName, fmOpenReadWrite);
except
on E: Exception do
begin
ShowMessage(E.Message);
Exit;
end
end;
input.Seek(i, SoFromBeginning);
input.Write(BytetoWrite[0], Length(BytetoWrite));
ShowMessage('Patch Success');
input.Free;
Exit;
end;
end;
ShowMessage('Patch Fail');
input.Free;
end;