Articles   Members Online:
-Article/Tip Search
-News Group Search over 21 Million news group articles.
-Delphi/Pascal
-CBuilder/C++
-C#Builder/C#
-JBuilder/Java
-Kylix
Member Area
-Home
-Account Center
-Top 10 NEW!!
-Submit Article/Tip
-Forums Upgraded!!
-My Articles
-Edit Information
-Login/Logout
-Become a Member
-Why sign up!
-Newsletter
-Chat Online!
-Indexes NEW!!
Employment
-Build your resume
-Find a job
-Post a job
-Resume Search
Contacts
-Contacts
-Feedbacks
-Link to us
-Privacy/Disclaimer
Embarcadero
Visit Embarcadero
Embarcadero Community
JEDI
Links
Fastest way to search a string in a file Turn on/off line numbers in source code. Switch to Orginial background IDE or DSP color Comment or reply to this aritlce/tip for discussion. Bookmark this article to my favorite article(s). Print this article
15-Sep-02
Category
Files Operation
Language
Delphi All Versions
Views
50
User Rating
No Votes
# Votes
0
Replies
0
Publisher:
DSP, Administrator
Reference URL:
DKB
			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;


			
Vote: How useful do you find this Article/Tip?
Bad Excellent
1 2 3 4 5 6 7 8 9 10

 

Advertisement
Share this page
Advertisement
Download from Google

Copyright © Mendozi Enterprises LLC