I was wondering if it was possible in VB6 to search a folder full of .dat files for a specific word in a .dat file? For instance, would I be able to make a program that searches for the word 'wire' in all of the .dat files in a folder then return a list of the files that contain the word?
This is a pretty basic example and is probably not too efficient with large files. It also assumes that the files are text not binary.
VB Code:
Option Explicit
Private Sub Form_Load()
Dim find As String
Dim fldr As String
fldr = "c:\somefolder\"
find = Dir$(fldr & "*.dat")
Do While Len(find)
SearchFile fldr & find, "wire"
find = Dir$()
Loop
End Sub
Public Sub SearchFile(ByVal fil As String, ByVal SearchFor As String)
Dim dat As String
Dim ff As Integer
ff = FreeFile()
On Error Goto Probs
Open fil For Input As #ff
dat = Input(LOF(ff), ff)
Close #ff
If InStr(1, dat, SearchFor, vbTextCompare) > 0 Then
MsgBox "Found it in file " & fil
End If
On Error Goto 0
Exit Sub
Probs:
MsgBox "Errors occurred!"
On Error Goto 0
End Sub
Ok, that code worked prefectly... at first. I decided to use .doc files (Microsoft Word) instead of .dat files. I took my test .dat files and just changed the extention to .doc and it still worked, it still found the word 'wire' in the .doc file. When I create a new .doc file and save it the program won't find it and it will go to the 'probs' part of the code.
Did I almost promise you more stuff to search files and their content on the PC/Net? This is an App I made for a factory that needed to lookup earlier test results saved in ".ATR"-files. Things that has to be changed are marked 'To be changed'.
Have fun!
Morten
When I create a new .doc file and save it the program won't find it and it will go to the 'probs' part of the code.
As I mentioned, the code I provided assumed you were working with text files. Word files are not pure text, they contain all sorts of formatting commands etc that can play havoc with that code. What was the error that occurred? Modify the error code like this and post the error...
VB Code:
Probs:
MsgBox "The following error occurred:" & vbCrLf & Error$
On Error Goto 0
Pete
No trees were harmed in the making of this post, however a large number of electrons were greatly inconvenienced.
Sorry it took so long for me to reply to this thread, I forgot to take the program home with me from work so I wasn't able to try anything over the weekend.
At any rate, the error was "Input Past End of File."
Also, that is a pretty slick program Ember. I'll be able to learn some stuff from it.