Author: William Gerbert Fastest way to search a string in a file Answer: The function below returns position of substring in file, or -1 if such substring can not be found. 1 2 function PosInFile(Str, FileName: string): integer; 3 var 4 Buffer: array[0..1023] of char; 5 BufPtr, BufEnd: integer; 6 F: file; 7 Index: integer; 8 Increment: integer; 9 c: char; 10 11 function NextChar: char; 12 begin 13 if BufPtr >= BufEnd then 14 begin 15 BlockRead(F, Buffer, 1024, BufEnd); 16 BufPtr := 0; 17 Form1.ProgressBar1.Position := FilePos(F); 18 Application.ProcessMessages; 19 end; 20 Result := Buffer[BufPtr]; 21 Inc(BufPtr); 22 end; 23 24 begin 25 Result := -1; 26 AssignFile(F, FileName); 27 Reset(F, 1); 28 Form1.ProgressBar1.Max := FileSize(F); 29 BufPtr := 0; 30 BufEnd := 0; 31 Index := 0; 32 Increment := 1; 33 repeat 34 c := NextChar; 35 if c = Str[Increment] then 36 Inc(Increment) 37 else 38 begin 39 Inc(Index, Increment); 40 Increment := 1; 41 end; 42 if Increment = (Length(Str) + 1) then 43 begin 44 Result := Index; 45 Break; 46 end; 47 until BufEnd = 0; 48 CloseFile(F); 49 Form1.ProgressBar1.Position := 0; 50 end;