读取文件内容的简洁方法

发表于:2007-06-21来源:作者:点击数: 标签:
读取text文件的最快方法是使用Input$函数,就象下面的过程: Function FileText (filename$) As String Dim handle As Integer handle = FreeFile Open filename$ For Input As #handle FileText = Input$(LOF(handle), handle) Close #handle End Function

   

读取text文件的最快方法是使用Input$函数,就象下面的过程:

Function FileText (filename$) As String

Dim handle As Integer

handle = FreeFile

Open filename$ For Input As #handle

FileText = Input$(LOF(handle), handle)

Close #handle

End Function

使用上述方法要比使用Input命令读取文件每一行的方法快很多。下面是应用这个函数读取Autoexec.bat的内容到多行textbox控件的例子:

Text1.Text = FileText("c:\autoexec.bat")

但请注意:当文件包含Ctrl-Z(EOF)字符时,上面的函数代码可能会发生错误。因此,要修改一下代码:

Function FileText(ByVal filename As String) As String

Dim handle As Integer

' 判断文件存在性

If Len(Dir$(filename)) = 0 Then

Err.Raise 53 '文件没有找到

End If

' 以binary模式打开文件

handle = FreeFile

Open filename$ For Binary As #handle

' 读取内容,关闭文件

FileText = Space$(LOF(handle))

Get #handle, , FileText

Close #handle

End Function

原文转自:http://www.ltesting.net