Solved

Searching for text in a file

Posted on 2004-08-12
6
196 Views
Last Modified: 2010-04-05
How can I know if some text can be find in a text file? I tried loading the file in a memo and then searching for it but when I have many and large files to look into it will take too much time.

thanks
0
Comment
Question by:sprinken
6 Comments
 
LVL 11

Expert Comment

by:Jase-Coder
ID: 11786379
you could put your code for loading the file and reading the file into a thread. This might make the performance better.
I am not sure if you can search a file without open and reading from it.
0
 
LVL 2

Expert Comment

by:beermequik
ID: 11788068
Use the TFindDialog component.  The help file describe it use pretty well.
0
 

Expert Comment

by:HorridMan
ID: 11789703
There is no way to search through data except one item at a time, from the first likely place to the last. The fastest method I can think of is to seek for just one character - just the first in the seek string - and when that is found, check if the next few characters in the file match the rest of the seek string.
You may also find it helpful to load as large an amount of data as possible at one time, if there is a lot to be searched through. Disk access is a timewaster, so loading small buffers as needed slows things down. If you're working with many small files, as long as they are all together in sequence on the disk, you could load several into one buffer.
Lastly, if speed is really imortant, then consider using delphi's Assembler to get the repetetive tasks, like the search loop, done more rapidly. This way there is nothing unnecessary going on behind the scenes.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 14

Accepted Solution

by:
Pierre Cornelius earned 80 total points
ID: 11790866
The following function will search any file (not just text files) for a specific string and return the position where it was found or alternatively -1 if it was not found.

(*With thanks to Peter Below*)
function ScanFile(const FileName: string; const forString: string; caseSensitive: Boolean): Longint;
const
  BufferSize = $8001;  { 32K+1 bytes }
var
  pBuf, pEnd, pScan, pPos: PChar;
  filesize: LongInt;
  bytesRemaining: LongInt;
  bytesToRead: Integer;
  F: file;
  SearchFor: PChar;
  oldMode: Word;
begin
  Result := -1;  // assume failure
  if (Length(forString) = 0) or (Length(FileName) = 0) then Exit;
  SearchFor := nil;
  pBuf      := nil;

  // open file as binary, 1 byte recordsize
  AssignFile(F, FileName);
  oldMode  := FileMode;
  FileMode := 0;    // read-only access
  Reset(F, 1);
  FileMode := oldMode; //reset to previous filemode

  try
    // allocate memory for buffer and pchar search string
    SearchFor := StrAlloc(Length(forString) + 1);
    StrPCopy(SearchFor, forString);
    if not caseSensitive  //convert to upper case
      then AnsiUpper(SearchFor);
    GetMem(pBuf, BufferSize);

    filesize       := System.Filesize(F);
    bytesRemaining := filesize;
    pPos           := nil;
    while bytesRemaining > 0 do
    begin
      // calc how many bytes to read this round
      if bytesRemaining >= BufferSize then
        bytesToRead := Pred(BufferSize)
      else
        bytesToRead := bytesRemaining;

      // read a buffer full and zero-terminate the buffer
      BlockRead(F, pBuf^, bytesToRead, bytesToRead);
      pEnd  := @pBuf[bytesToRead];
      pEnd^ := #0;

      pScan := pBuf;
      while pScan < pEnd do
      begin
        if not caseSensitive // convert to upper case
          then AnsiUpper(pScan);
        pPos := StrPos(pScan, SearchFor);  // search for substring
        if pPos <> nil then
        begin // Found it!
          Result := FileSize - bytesRemaining +
            Longint(pPos) - Longint(pBuf);
          Break;
        end;
        pScan := StrEnd(pScan);
        Inc(pScan);
      end;
      if pPos <> nil then Break;
      bytesRemaining := bytesRemaining - bytesToRead;
      if bytesRemaining > 0 then
      begin
        Seek(F, FilePos(F) - Length(forString));
        bytesRemaining := bytesRemaining + Length(forString);
      end; //if
    end; // While
  finally
    CloseFile(F);
    if SearchFor <> nil then StrDispose(SearchFor);
    if pBuf <> nil then FreeMem(pBuf, BufferSize);
  end; //try, finally
end;


USAGE:
If you just want to know if the file contains a string, you would do this:
  if ScanFile('YourFileToSearch.txt'; 'StringToLookFor'; false) = -1
    then ShowMessage('String Found!')
    else ShowMessage('String Not Found!');

This function works pretty fast and I'm sure will solve your problem.

Kind Regards
Pierre Cornelius
0
 

Author Comment

by:sprinken
ID: 11805183
Thanks Pierre! Sorry for being late
0
 
LVL 14

Expert Comment

by:Pierre Cornelius
ID: 11830994
Glad I could help
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction The parallel port is a very commonly known port, it was widely used to connect a printer to the PC, if you look at the back of your computer, for those who don't have newer computers, there will be a port with 25 pins and a small print…
Have you ever had your Delphi form/application just hanging while waiting for data to load? This is the article to read if you want to learn some things about adding threads for data loading in the background. First, I'll setup a general applica…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now