Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

check txt file for a word

Status
Not open for further replies.

mkzw0ot4m0nk

Programmer
Jul 19, 2002
29
0
0
US
hey, how can i check a txt file for a word?
 
One simple way is to use a stringlist...

function in_file(filename : string;
text2find : string;
casesense : boolean) : boolean;
var sl : tstringlist;
begin
result := false;
sl := tstringlist.create;
try
sl.loadfromfile(filename);
if casesense
then result := (pos(text2find,sl.text) > 0)
else result := (pos(uppercase(text2find),
uppercase(sl.text)) > 0);
finally
sl.free;
end;
end;

This approach has a few limits. Most notably, it loads the entire file into memory before testing, so it might be slow on large files. If the file is very large, this method might not provide accurate results because stringlist has a capacity limit and the exception (raised by exceeding that capacity) sends the same false result value as not finding the text in a normal size file sends.

Still, it is quick to code, simple to understand and will work most of the time.
Hope it helps.
Peace,
Colt.
 
You may want to try the following as an alternative if you wish -

function TextSearch ( sFile, sText : string, lCase : boolean ) : boolean;
var
fSearchFile : File;
sFileContent : String;
begin
{ Open file }
AssignFile( fSearchFile, sFile );

{ Read entire file into a string variable and then close }
Read( fSearchFile, sFileContent );
CloseFile( fSearchFile );

if ( lCase ) then
Result := ( Pos( sText, sFileContent ) > 0 )
else
Result := ( Pos( UpperCase( sText ), UpperCase( sFileContent ) ) > 0 );

end;


Delphi does not report any size limitations when reading an entire file like this. This function assume sFile exists.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top