procedure TForm1.Button1Click(Sender: TObject);type THeader = record Count: dword; end;var Header: THeader; i, k, Count: integer; ms1, ms2, ms3: TMemoryStream; S: string;begin ms1:= TMemoryStream.Create; ms2:= TMemoryStream.Create; ms3:= TMemoryStream.Create; try ms1.LoadFromFile('c:/f1.dat'); ms2.LoadFromFile('c:/f2.dat'); S:= ''; ms1.Position:= 0; ms2.Position:= 0; while ms2.Position < ms2.Size do begin ms2.Read(Header, SizeOf(Header)); Count:= Header.Count; ms3.Clear; ms3.CopyFrom(ms2, Header.Count); k:= FindStream(ms1, ms3); //从f1.dat中查找出现的位置 if k >= 0 then begin S:= S + Format('%d:%d', [k, Count]) + #13#10; //位置:长度 end; ms2.Position:= ms2.Position + SizeOf(Header) + Count; end; if S <> '' then begin S:= Copy(S, 1, Length(S) - 2); ms1.Clear; ms1.Write(S[1], Length(S)); ms1.Position:= 0; ms1.SaveToFile('c:/f3.txt'); end; finally ms1.Free; ms2.Free; ms3.Free; end;end;function TForm1.FindStream(Stream, SubStream: TMemoryStream): integer; function CompareStream(Stream1, Stream2: TMemoryStream; StartPos1, StartPos2, Count: integer): Boolean; var ii: integer; p1, p2: pbyte; begin result:= false; p1:= pbyte(Stream.Memory^); p2:= pbyte(SubStream.Memory^); inc(p1, StartPos1); inc(p2, StartPos2); for ii:= 0 to Count - 1 do begin if p1^ <> p2^ then exit; inc(p1); inc(p2); end; result:= true; end;var i, j, k, OldPos1, OldPos2: integer;begin result:= -1; OldPos1:= Stream.Position; OldPos2:= SubStream.Position; try Stream.Position:= 0; SubStream.Position:= 0; for i:= 0 to Stream.Size - SubStream.Size - 1 do begin if not CompareStream(Stream, SubStream, i, 0, SubStream.Size) then Continue; result:= i; break; end; finally Stream.Position:= OldPos1; //恢复以前保存的位置 SubStream.Position:= OldPos2; end;end;