打印本文 打印本文  关闭窗口 关闭窗口  
读取文件内容的简洁方法
作者:佚名  文章来源:不详  点击数  更新时间:2008/5/9 19:02:25  文章录入:杜斌  责任编辑:杜斌

  读取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

打印本文 打印本文  关闭窗口 关闭窗口