用递归法查找文件
来源:百度文库 编辑:神马文学网 时间:2024/04/29 19:33:12
具体做法是:编写一个扫描文件夹(Scan),当遇到子文件夹时中断当前文件夹的扫描,开始扫描子文件夹,即调用过程本身,如子文件夹中还有子文件夹,就采取相同的方法继续调用过程,直至文件夹(子文件夹)中不再含有子文件夹为止。
程序涉及的控件及需改变的缺省属性如下:
1.一个DriveListBox控件。
2.一个DirListBox控件。
3.一个ListBox控件,该控件用来显示查找到的文件。
4.两个CommandButton控件。
5.一个StatusBar控件,该控件用来显示查找到的文件个数,Style属性置为1,SimpleText属性置为“”。
6.两个OptionButton控件,其中Option1的Value属性置为True。
7.两个TextBox控件,Text属性都置为“”,其中Text1用来设置待查找文件的文件名,Text2用来设置待查找文件的扩展名,Text2的Enabled置为False,MaxLength属性置为3。
8.两个Frame控件。
以下是程序清单:
Option Explicit
Public Sub scan(a As String)
Dim filename As String
Dim nd As Integer
Dim fold() As String
Dim n As Integer
filename = Dir(a)
Do While filename <> “”
If Option1.Value =True Then
If LCase(filename) = LCase(Text1.Text) Then
List1.AddItem (a & filename)
End If
Else
If LCase(Right(filename, 3)) = LCase(Text2.Text) Then
List1.AddItem (a & filename)
End If
End If
filename = Dir
Loop
filename = Dir(a, vbDirectory)
Do While filename <> “”
If filename <>“.” And filename <> “..” Then
If GetAttr(a & filename) = vbDirectory Then
nd = nd + 1
ReDim Preserve fold(nd)
fold(nd) = a & filename
End If
End If
filename = Dir
DoEvents
Loop
For n = 1 To nd
scan fold(n) & “\”
Next
If List1.ListCount = 0 Then
StatusBar1.SimpleText = “No file discovery”
Else
StatusBar1.SimpleText = List1.ListCount & “file(s) discovery”
End If
End Sub
Private Sub Command1_Click()
Dim searchfold As String
List1.Clear
StatusBar1.SimpleText = “”
If Right(Dir1.Path, 1) = “\” Then
searchfold = Left(Dir1.Path, 2)
Else
searchfold = Dir1.Path
End If
Me.MousePointer = vbHourglass
scan searchfold & “\”
Me.MousePointer = vbDefault
End Sub
Private Sub Command2_Click()
Unload Me
End Sub
Private Sub Drive1_Change()
On Error GoTo a
Dir1.Path = Drive1.Drive
Exit Sub
a:
If Left(Drive1.Drive, 1) = “a” Then
MsgBox “Floppy drive is not be ready!”, vbCritical
End If
End Sub
Private Sub Option1_Click()
Text1.Enabled = True
Text2.Enabled = False
End Sub
Private Sub Option2_Click()
Text1.Enabled = False
Text2.Enabled = True
End Sub
最后,再对程序代码作进一步的说明:
1.过程(Scan)的参数a由DirListBox控件的选项决定,可以是硬盘盘符,如C:\(扫描整个分区),也可以是目录路径,如C:\Windows(仅扫描该目录)。
2.Dir函数是过程中的关键。该函数的作用是查找任何驱动器上的文件或目录。如果调用带参数的Dir函数再调用不带参数的Dir函数,则函数将从当前要搜索的目录中返回与上一次指定参数相匹配的下一个文件,这就使遍历一个目录中的所有文件成为可能。
3.程序中的错误处理语句:On Error GoTo a不能省略。这是因为如果软驱中没有软盘,Drive1_Change()过程会出错。