views:

123

answers:

1

I want to check a file has a valid IMAGE_DOS_SIGNATURE (MZ)

function isMZ(FileName : String) : boolean;
var
 Signature: Word;
 fexe: TFileStream;
begin
result:=false;
try
  fexe := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone);
  fexe.ReadBuffer(Signature, SizeOf(Signature));
  if Signature = $5A4D { 'MZ' } then
  result:=true;
finally
fexe.free;
end;
end;

I know I can use some code in Windows unit to check the IMAGE_DOS_SIGNATURE. The problem is I want the fastest way to check IMAGE_DOS_SIGNATURE (for a big file). I need your some suggestion about my code or maybe a new code?

Thanks

+4  A: 

The size of the file doesn't matter because your code only reads the first two bytes.

Any overhead from allocating and using a TFileStream, which goes through SysUtils.FileRead before reaching Win32 ReadFile, ought to be all but invisible noise compared to the cost of seeking in the only situation where it should matter, where you're scanning through hundreds of executables.

There might possibly be some benefit in tweaking Windows' caching by using the raw WinAPI, but I would expect it to be very marginal.

Barry Kelly
Yes I want to scan through hundreds of executables, so I am looking for the fast code.Ok, you're right the value of SizeOf(Signature) is 2. Can you explain me why the value is 2, because the value of Signature has not been declared?
`SizeOf(Signature)` is 2 because Signature has been declared as `word` and the size of a `word` is 16 bits, ie 2 bytes.
MikeJ-UK
Thanks. last question, if the file size of FileName is zero, I got "stream read error". I can handle this problem by using try except. Is there any internal method to know fexe will cause error?
Before calling `fexe.ReadBuffer` check that `fexe.Size > 2` or better, greater than the minimum valid size for a Windows PE format file (I don't know what that is off-hand).
MikeJ-UK
Instead of calling ReadBuffer, call Read and check the return value; it will tell you how many bytes it read. If it doesn't return 2, then the file doesn't have a valid signature.
Rob Kennedy