Jump to content
Tuts 4 You

[Delphi] Get Offset By A/B


0xFF

Recommended Posts

This little function will return an offset inside a binary typed file by a given array of byte.

function RetOffset(const FileName: String; const bSrc: Array Of Byte): DWORD;  
var
hFile : DWORD;
CompareArray : Array Of Byte;
FileLength : DWORD;
Pos : DWORD;
BytesRead : DWORD;
begin
Result := 0;
Pos := 0;
hFile := CreateFile(PChar(FileName), GENERIC_READ, 0, nil, OPEN_EXISTING, 0, 0);
If hFile = INVALID_HANDLE_VALUE Then Exit;
SetLength(CompareArray, Length(bSrc));
Try
FileLength := SetFilePointer(hfile, 0, nil, FILE_END) - Length(bSrc);
SetFilePointer(hFile, 0, nil, FILE_BEGIN);
While Pos <= FileLength Do
begin
If ReadFile(hFile, CompareArray[0], Length(CompareArray), BytesRead, nil) Then
begin
If CompareMem(PByteArray(@bSrc[0]), PByteArray(@CompareArray[0]), Length(bSrc)) Then
begin
Result := Pos;
Break;
end;
Inc(Pos, 1);
SetFilePointer(hFile, Pos, nil, FILE_BEGIN);
end
Else
begin
Break;
end;
end;
Finally
CompareArray := nil;
CloseHandle(hFile);
end;
end;
Edited by rotem156
Link to comment

Nice code!

A couple of tips for Delphi coders:

The array of Byte type can also be used as TByteDynArray, you just need to add in uses the unit Types. There are a lot of predefined types there! :)

Pos is a Delphi function, if you use it as a variable you are redefining it and it won't be possible to use in your code as a function. Although doing in that way is not an error, though.

Best regards

Nacho_dj

Link to comment

Nacho,

So whats the differences between an "Array of Byte" and "TByteDynArray"? Just interested because I have always put it into a Array of Byte, Have never used "TbyteDynArray" type.

Link to comment

This is very useful when you want to code a function giving as result an array of Byte type. Well, Delphi compiler does not allow you define such a function, however if you define the type of the result of that function as TByteDynArray, it will be accepted by the compiler... ;)

Cheers

Nacho_dj

Link to comment

Nacho,

So whats the differences between an "Array of Byte" and "TByteDynArray"? Just interested because I have always put it into a Array of Byte, Have never used "TbyteDynArray" type.

Nothing, it's just instead of writing array of byte you will make the code look more tidier by writing a predefined definition.

Link to comment

Well, there is also TCardinalDynArray = array of Cardinal, and much more...

I was defining my own types for array of anything, till I found that library, that I never heard before of. Now it is used in all my tools, since when dealing with files always use array of Byte.

Best regards

Nacho_dj

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...