Using FreePascal (or Delphi if no FP examples), given a 2048 byte buffer that is as an "array of bytes", how can I search the buffer for "StringA"?
var Buffer : array[1..2048] of byte; ... repeat i := 0; BlockRead(SrcFile, Buffer, SizeOf(Buffer), NumRead); // Now I want to search the buffer for "StringA"? ...
I think this will work in fpc without extra Unicode/AnsiString conversion :
function Find(const buf : array of byte; const s : AnsiString) : integer; //returns the 0-based index of the start of the first occurrence of S //or -1 if there is no occurrence var AnsiStr : AnsiString; begin SetString(AnsiStr, PAnsiChar(@buf), Length(buf)); Result := Pos(s,AnsiStr) - 1; // fpc has AnsiString overload for Pos() end;
Here's the naïve approach whereby we simply walk through the buffer byte by byte looking for the desired string.
function Find(const Buffer: array of Byte; const S: AnsiString): Integer; //returns the 0-based index of the start of the first occurrence of S //or -1 if there is no occurrence var N: Integer; begin N := Length(S); if N>0 then for Result := low(Buffer) to high(Buffer)-(N-1) do if CompareMem(@Buffer[Result], Pointer(S), N) then exit; Result := -1; end;
I don't use FPC but I expect that this will work unchanged and if not then I'm sure you can convert it.