Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: VB4,VB5,VB6
Expertise: beginner
Apr 20, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Load a text file in one operation

The fastest way to read a text file is using the Input$ function, as shown in this reusable procedure:

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
This method is much faster than reading each single line of the file using a Line Input statements. Here's how you can load a multiline textbox control with the contents of Autoexec.bat:

Text1.Text = FileText("c:\autoexec.bat")
UPDATE: Andrew Marshall wrote us to point out that the above routine fails when the file includes a Ctrl-Z (EOF) character, so we prepared a better version that works around that problem:

Function FileText(ByVal filename As String) As String
    Dim handle As Integer
    ' ensure that the file exists
    If Len(Dir$(filename)) = 0 Then
        Err.Raise 53   ' File not found
    End If
    ' open in binary mode
    handle = FreeFile
    Open filename$ For Binary As #handle
    ' read the string and close the file
    FileText = Space$(LOF(handle))
    Get #handle, , FileText
    Close #handle
End Function
Francesco Balena
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date