File I/O Tutorial-VBForums
Results 1 to 6 of 6

Thread: File I/O Tutorial

  1. #1

    Thread Starter
    Banned plenderj's Avatar
    Join Date
    Jan 2001
    Location
    Dublin, Ireland
    Posts
    10,359

    File I/O Tutorial

    ** Please see next post for an update of code.
    **

    Open Statement
    File IO in visual basic is initiated by the Open statement.
    Syntax for the Open statement is as follows ;

    Open pathname For mode [Access access] [lock] As [#]filenumber [Len=reclength]


    It looks quite complicated, but in fact it isnt.
    If we want to read data from a file, we would open it as follows ;
    VB Code:
    1. Open "c:\somefile.vbw" For Input As #1

    If on the other hand we wanted to write to the file then ;
    VB Code:
    1. Open "c:\somefile.vbw" For Output As #1


    There are 3 other ways of opening files.
    VB Code:
    1. Open "c:\somefile.vbw" For Append As #1
    2.     Open "c:\somefile.vbw" For Binary As #1
    3.     Open "c:\somefile.vbw" For Random As #1

    If you do not specify how the file is to be opened,
    Visual Basic will assume Random mode.




    Close Statement
    When we've finished working with our file we should close it.
    Reason being that we might forget to later in our code,
    or if we try to open another file with the same file number,
    the we'll get a runtime error.

    So we close a file as follows :
    VB Code:
    1. Close #1

    It doesnt matter what File IO mode we were in, Close #filenumber
    applies for each mode.
    Here are some examples :
    VB Code:
    1. Open "c:\somedir\myFile" For Output As #1
    2.        
    3.     Close #1
    4.  
    5.  
    6.     Open "\\someserver\somefolder\somefile" For Random As #1
    7.        
    8.     Close #1

    It is normally good practice, that when you put an Open statement
    into your code, you also at the same time put a Close statement
    below it. You then fill in the code in the middle with the actual
    file IO work that you want done.




    The IO Work Itself
    By now we should know how to both Open and Close any given file.
    But we don't yet know how to actually do anything with the file.

    So how do we read data from the file ?
    There are a number of ways. Starting off with the simplest would
    be using the Line Input statement.

    VB Code:
    1. Dim strBuff As String
    2. Open "c:\autoexec.bat" For Input As #1
    3.     Line Input #1, strBuff
    4.     'strBuff now contains the first line of autoexec.bat
    5. Close #1

    Subsequent calls of the Line Input statement will
    cause subsequent lines of the opened file to be read in.
    So its obvious then that if we do many subsequent calls of this statement
    we could read in the entire file ;

    VB Code:
    1. Dim strBuff As String
    2. Open "c:\autoexec.bat" For Input As #1
    3.     Do
    4.         Line Input #1, strBuff
    5.         Debug.Print strBuff
    6.     Loop
    7. Close #1

    The above code will read in the entire file, but there is no condition
    in that Do Loop so the code will keep trying
    to read in lines from the file. For those of you interested, Visual Basic
    will throw runtime error 62 : Input past end of file.

    So how do we keep reading lines in from the file, while we're not at
    the End of the file ? Or to put it another way, how do we keep reading
    lines in from the file until we reach the end of the file ?
    Well there is a function EOF() which will return a
    boolean value {True,False} indicating whether or not we've reached the
    end of the file. Here's an example of how to use it :

    VB Code:
    1. Dim strBuff As String
    2. Open "c:\autoexec.bat" For Input As #1
    3.     Do Until Eof(1)
    4.         Line Input #1, strBuff
    5.         Debug.Print strBuff
    6.     Loop
    7. Close #1

    So the above code will keep reading in data until the end of the file.
    Each line of the file is read into strBuff though.
    But what if we wanted to store the information in an array so that we
    can access the data later ? Well for this the obvious approach would
    be to use a Dynamic Array ;

    VB Code:
    1. Dim strArray() As String
    2. ReDim strArray(0)
    3. Open "c:\autoexec.bat" For Input As #1
    4.     Do Until EOF(1)
    5.         Line Input #1, strArray(UBound(strArray))
    6.         ReDim Preserve strArray(UBound(strArray) + 1)
    7.     Loop
    8. Close #1

    So the entire file is stored, line by line, in the strArray array.
    But there's an even faster way of doing this.
    There is another File IO function called Input().
    This will read in a specific number of bytes of a file into a String.
    So we can read the entire file into a String buffer using this function.
    All we need is a way of finding out the size of the file.
    This is where the LOF() functions comes in.
    LOF() will return the size of the file whose
    file number is passed to the function.

    So here are examples of how the functions work :

    VB Code:
    1. Open "c:\autoexec.bat" For Input As #1
    2.     MsgBox "Length of file : " & LOF(1)
    3.     MsgBox "First 20 bytes of file #1 : " & Input(20, 1)
    4. Close #1

    So then we could combine the two functions to read the entire file into
    a buffer all at once :

    VB Code:
    1. Dim strBuff As String
    2. Open "c:\autoexec.bat" For Input As #1
    3.     strBuff = Input(LOF(1), 1)
    4.     MsgBox strBuff
    5. Close #1

    So we now have the entire file in a String buffer.
    And what if we wanted to store the String buffer as an array ?
    Well imagine as file as being one really long line of text.
    Instead of having different lines we have delimeters of vbCrLf characters.
    So strBuff essentially contains one long String of text delimeted with
    these special vbCrLf characters.

    There's a very handy function in Visual Basic 6 that will take a String of
    text, and given specific delimeters, will return an array.
    The function is the Split() function.
    Here's a few examples :

    VB Code:
    1. Dim strBuff() As String
    2. Dim myString As String
    3.  
    4. myString = "a,b,c,d"
    5. strBuff = Split(myString, ",")
    6. MsgBox "Array element 0 : " & strBuff(0)
    7.  
    8. myString = "VB Forums|[url]http://www.vbforums.com[/url]|Blah!"
    9. strBuff = Split(myString, "|")
    10. MsgBox "Array Element 2 : " & strBuff(2)
    11.  
    12. myString = "a b c"
    13. MsgBox "Array Element 1 : " & Split(myString, " ")(1)

    So how do we do it with File IO ?

    VB Code:
    1. Dim strArray() As String
    2. Open "c:\autoexec.bat" For Input As #1
    3.     strArray = Split(Input(LOF(1), 1), vbCrLf)
    4. Close #1

    So the above 3 lines of code will take the entire contents of a file,
    read it in line by line, and store the data in an array.
    This, as far as I know, is the best and fastest way of reading the contents
    of a file into an array.
    Last edited by plenderj; Dec 2nd, 2001 at 12:30 PM.

  2. #2

    Thread Starter
    Banned plenderj's Avatar
    Join Date
    Jan 2001
    Location
    Dublin, Ireland
    Posts
    10,359
    I suggest that you use the following code for reading data from a file instead:

    VB Code:
    1. Open strSomeFile For Binary As #1
    2.     Dim strBuff As String
    3.     strBuff = Space(Lof(1))
    4.     Get #1, , strBuff
    5. Close #1

    Samples of this are given in the 2nd post of this thread

    This is because if you open a Binary file using the Input mode, it will nearly certainly fail once it hits binary characters.
    But if you open for Binary, and use the different input procedure, then you can open both text and binary files.

    Using the Get, , #FileNumber is also very fast!

  3. #3
    Lively Member
    Join Date
    Aug 2009
    Posts
    99

    Re: File I/O Tutorial

    On this example, what would i need to do in order to read the file into an array last line first?
    Dim strArray() As StringReDim strArray(0)Open "c:\autoexec.bat" For Input As #1 Do Until EOF(1) Line Input #1, strArray(UBound(strArray)) ReDim Preserve strArray(UBound(strArray) + 1) LoopClose #1

  4. #4
    VB For Fun Edgemeal's Avatar
    Join Date
    Sep 2006
    Location
    WindowFromPoint
    Posts
    3,629

    Re: File I/O Tutorial

    Quote Originally Posted by supercrewed View Post
    On this example, what would i need to do in order to read the file into an array last line first?
    Maybe try something like this,
    Code:
    Option Explicit
    
    Private Sub Command1_Click()
        
        Dim L As Long
        Dim MyArray() As String
        
        ' Load file into string array
        FileToArray "C:\TEST.txt", MyArray
        
        ' Reverse array contents
        ReverseStrArray MyArray
        
        ' show result in immediate window
        For L = 0 To UBound(MyArray)
            Debug.Print MyArray(L)
        Next L
        
    End Sub
    
    Private Sub FileToArray(ByVal sPath As String, ByRef sArray() As String)
        Dim ff As Integer
        ff = FreeFile
        On Error GoTo Fini
        Open sPath For Input As #ff
        sArray = Split(Input(LOF(ff), ff), vbCrLf)
    Fini:
        Close #ff
    End Sub
    
    Private Sub ReverseStrArray(ByRef sArray() As String)
        Dim ubnd As Long, lbnd As Long, x As Long
        Dim sTmp As String
        ubnd = UBound(sArray)
        lbnd = LBound(sArray)
        For x = lbnd To ((ubnd - lbnd - 1) \ 2)
          sTmp = sArray(lbnd + x)
          sArray(lbnd + x) = sArray(ubnd - x)
          sArray(ubnd - x) = sTmp
        Next x
    End Sub

  5. #5
    Member
    Join Date
    Sep 2008
    Location
    Turkey
    Posts
    37

    Re: File I/O Tutorial

    Thanks For Share...

  6. #6
    New Member
    Join Date
    Apr 2011
    Posts
    13

    Re: File I/O Tutorial

    Great tutorial , helped me a lot. Thanks !!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.