Avatar of SDfatha
SDfatha
Flag for Afghanistan asked on

How to verify that a word exist on a .txt file using Visual Basic v6

I need a code which will open a .txt file and search for a certain word and if word exist to get a msgbox.

I need something like,

Open "test.txt" for input as #1
Search for word 'example'
msgbox if word exist
do nothing if not exist

Thank you!
Visual Basic Classic

Avatar of undefined
Last Comment
Martin Liss

8/22/2022 - Mon
Martin Liss

Dim strBuffer As String
Open "c:\MyPath\Test.txt" For Input As #1
strBuffer = Input(LOF(1), 1)
If Instr(1, strBuffer, "example") Then
     MsgBox "It's there'
End If
Close #1
Martin Liss

Here's better code with comments.


Dim strBuffer As String
' Define an Integer to hold the file number
Dim FF As Integer

' Find a file number that's not in use
FF = FreeFile

Open "c:\temp\Test.txt" For Input As #FF

' The format of 'Input' is Input(how-many-bytes, file-number) and
' LOF is Length Of File so how-many-bytes is set at length of the file
strBuffer = Input(LOF(FF), FF)
If InStr(1, strBuffer, "example") Then
     MsgBox "It's there'"
End If
Close #FF
ASKER CERTIFIED SOLUTION
HooKooDooKu

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Martin Liss

Wouldn't doing InStr on a large file line by line be pretty slow.

As an alternative the file could be read in large chunks using Input.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
HooKooDooKu

But if you read it in chunks, a chunk might end in the middle of the text you are looking for.  By reading a line at a time, you are assured that each 'chunk' ends on a Carriage Return.

Besides, if your computer has good disk reading buffers, there should be a huge performance difference.

Either InStr searches something like 100 byte buffers 10,000 times, or it searches 10,000 byte buffers 100 times.  Either way InStr has to process 1,000,000 of memory.  Yes, there will be some performance boost because InStr is called fewer times with larger memory chunks (and the same can be said about disk reads).  But adding a few thousand function calls should affect over all speed greatly, so long as the disk reading logic has good buffering (because I/O is going to be your bottle neck, not multiple function calls).
Martin Liss

But if you read it in chunks, a chunk might end in the middle of the text you are looking for.

Good point.