PowerUser
PowerUser

Reputation: 11791

This code works, but how?

I just wrote this function to read a series of email addresses from a linebreak-delimited text file. And it does work, but that's not my question.

Function GetEmailArray(FileName As String) As String()
    Dim TempArr() As String
    Dim i As Integer

    Open FileName For Input Access Read As #1
    Do While Not (EOF(1))
        i = i + 1
        ReDim Preserve TempArr(i + 1)
        Line Input #1, TempArr(i + 1)
        Debug.Print TempArr(i + 1)
    Loop
    Close #1
    GetEmailArray = TempArr
End Function

Reading this, I would expect this to:

  1. Read the first line, store it in TempArr(1)
  2. Loop
  3. Read the first line AGAIN, store it in TempArr(2)
  4. Loop
  5. Etc

I just can't figure out how the while loop goes to the next line in the text file.

Upvotes: 0

Views: 167

Answers (4)

GvS
GvS

Reputation: 52518

Your step 3 should be:

3. Read the next line from the file into TempArr(i + 1)

So you do not read in the first line again, the line input statement reads the line, and places the file-position on the next line.

Upvotes: 2

Rushyo
Rushyo

Reputation: 7604

The Line Input function is altering the current line. Pretty tacky stuff.

Upvotes: 0

Pontus Gagge
Pontus Gagge

Reputation: 17258

You're holding a handle (#1) to the file from the point you call Open, until you call Close. Behind the scenes (on the O/S level), the handle retains a current file position as part of the file descriptor.

Upvotes: 2

I believe the magic is happening on Line Input #1, TempArr(i+1). It reads from file handle #1 to TempArr(i+1). When it gets to the end of the file, EOF(1) will evaluate to true and terminate the while loop. How does the system know which is the next line? That's handled under the hood for you, by Line Input.

Upvotes: 1

Related Questions