Reading a sequential file into an array

In our note on reading and displaying a sequential file, we wrote a loop that processed a sequential file from its first through last records. In that example, we read and displayed each record in sequence until reaching the end of the file.

That is a common way to process records in a sequential file. For example, the Gas Company billing program reads through the customer file, printing a bill for each account record or a payroll program reads through a personnel file, printing a pay check for every employee record.

It is also common to read a file into an array so that it can be processed randomly. That is illustrated by this program which reads the entire friends.txt file into an array when the user clicks btnRead, then allows the user to display records at random:

Dim Friends(100) As String
Private Sub btnRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRead.Click
        Dim nameFile As IO.StreamReader
        Dim recordPointer As Integer
        nameFile = New System.IO.StreamReader(txtfile.Text)
        Do Until nameFile.Peek = -1
            Friends(recordPointer) = nameFile.ReadLine
            recordPointer = recordPointer + 1
        Loop
        nameFile.Close()
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
   Dim i As Integer
   i = CInt(tbxRecordNumber.Text)
   lblOut.Text = Friends(i - 1)
End Sub

The program has two event handlers. The first is executed when the user clicks btnRead. It is a loop that reads the entire friends.txt file into an array called Friends. The loop reads the records one at a time using the ReadLine method of the StreamReader called nameFile. Each successive record is assigned to the next open element in the array Friends. The subscript of the next open element is in the integer variable recordPointer which is incremented by 1 at the end of each iteration, It may be helpful to think of recordPointer as pointing to the next available array element as the program executes.

Note that the array Friends is global to the entire form or module, and that I allowed subscripts up to 100 because I wanted to be sure to leave enough space for the file, regardless of its length.

The second event handler is executed after the program has loaded and the Friends array has been initialized. When the user clicks on the OK button, the array element that he or she has entered into tbxRecordNumber is displayed in lblOut.

Note that the subscript is one less than the requested record number because the array elements are numbered from zero.


Disclaimer: The views and opinions expressed on unofficial pages of California State University, Dominguez Hills faculty, staff or students are strictly those of the page authors. The content of these pages has not been reviewed or approved by California State University, Dominguez Hills.