DelphiFAQ Home Search:

Fastest way to search a string in a file

 

comments6 comments. Current rating: 4 stars (5 votes). Leave comments and/ or rate it.

The function below returns position of substring in file, or -1 if such substring can not be found.

Better: use the Boyer-Moore algorithm. There's a Pascal implementation at
http://www.dcc.uchile.cl/~rbaeza/handbook/algs/7/713b.srch.p.html.

function PosInFile(Str,FileName:string):integer;
var
   Buffer : array [0..1023] of char;
   BufPtr,BufEnd:integer;
   F:File;
   Index : integer;
   Increment : integer;
   c : char;

function NextChar : char;
 begin
   if BufPtr>=BufEnd then
   begin
     BlockRead(F,Buffer,1024,BufEnd);
     BufPtr := 0;
     Form1.ProgressBar1.Position := FilePos(F);
     Application.ProcessMessages;
   end;
   Result := Buffer[BufPtr];
   Inc(BufPtr);
 end;

 begin
   Result := -1;
   AssignFile(F,FileName);
   Reset(F,1);
   Form1.ProgressBar1.Max := FileSize(F);
   BufPtr:=0;
   BufEnd:=0;
   Index := 0;
   Increment := 1;
   repeat
     c:=NextChar;
     if c=Str[Increment] then
       Inc(Increment)
     else
     begin
       Inc(Index,Increment);
       Increment := 1;
     end;
     if Increment=(Length(Str)+1) then
     begin
       Result := Index;
       break;
     end;
   until BufEnd = 0;
   CloseFile(F);
   Form1.ProgressBar1.Position := 0;
 end;

Comments:

2005-11-09, 23:56:30
kapilpatil84group@yahoo.com from India  
rating
2005-11-30, 02:48:17
mailparikshit@yahoo.com from India  
rating
can you explain this code or translate this code in c/c++,vb
2006-02-04, 07:21:03
hodonkain@hotmail.com from United States  
rating
Can you explain the processes?... whats going on at each process?
I program in DirectX and would like to know whats going on at each step so I can
translate it into my code. -thx
2008-04-22, 14:27:34
anonymous  
Nice trick thnx alot.
2010-04-20, 11:05:24
anonymous from Saudi Arabia  
rating
Great!
2013-09-06, 08:23:54
anonymous from Italy  
rating

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: