开发者

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.


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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜