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
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
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.
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