Home All Groups Group Topic Archive Search About

read whole file at once

Author
22 Sep 2005 6:07 PM
Robert Dormer
Hello,

Can anyone tell me how to read a file (text or otherwise) into a buffer so
that the whole file ends up in the buffer, instead of reading it line by
line?

Author
22 Sep 2005 7:17 PM
Jim Edgar
"Robert Dormer" <r.dor***@www.digdevinc.com> wrote in message
news:%234M6ej6vFHA.3452@TK2MSFTNGP14.phx.gbl...
> Hello,
>
> Can anyone tell me how to read a file (text or otherwise) into a buffer so
> that the whole file ends up in the buffer, instead of reading it line by
> line?
>
>

Here's a snippet from one of my projects.  You'll need to declare the
variable
first.

    ' Open the file to be parsed.
    iFileNum = FreeFile
    Open strPath & strFileName For Binary As #iFileNum
    ' Get the file information.
    str = Space(LOF(iFileNum))
    Get #iFileNum, , str
    ' Done with the file so close it.
    Close #iFileNum

Jim Edgar
Author
22 Sep 2005 11:35 PM
Mike D Sutton
> Can anyone tell me how to read a file (text or otherwise) into a buffer so
> that the whole file ends up in the buffer, instead of reading it line by
> line?

These functions will read a file into a string or byte array respectively:

'***
Private Function FileToString(ByRef inFile As String) As String
    Dim FNum As Integer

    FNum = FreeFile()
    Open inFile For Binary Access Read Lock Write As #FNum
        FileToString = Space$(LOF(FNum))
        Get #FNum, , FileToString
    Close #FNum
End Function

Private Function FileToBuf(ByRef inFile As String, ByRef OutBuf() As Byte) As Long
    Dim FNum As Integer

    FNum = FreeFile()
    Open inFile For Binary Access Read Lock Write As #FNum
        FileToBuf = LOF(FNum)
        ReDim OutBuf(0 To FileToBuf - 1) As Byte
        Get #FNum, , OutBuf()
    Close #FNum
End Function
'***

The latter would be faster (and more appropriate for binary data), but it really depends on what you want to do with it.
Hope this helps,

    Mike


- Microsoft Visual Basic MVP -
E-Mail: ED***@mvps.org
WWW: Http://EDais.mvps.org/