55George Washington 50Martha Washington 8Abraham Lincoln 8Mary Lincoln 9John F. Kennedy 7Jacqueline Kennedy 42Dwight D. Eisenhower 47Mamie Eisenhower 60Harry Truman 65Bess TrumanIt has two fields per record:
Field 1: columns 1-2, age Field 2: column 3 to end, nameThese are fixed format records, with the same columns being used for each field (note the alignment of the Lincoln's and Kennedy's ages).
The following is a program to list each person's name and age:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'open the friendsAge file Dim ageFile As System.IO.StreamReader ageFile = New System.IO.StreamReader(txtfile.Text) 'declare working variables Dim strRecord, name As String Dim age, RecordCount As Integer 'read and display records one at a time Do While ageFile.Peek <> -1 strRecord = ageFile.ReadLine age = CInt(strRecord.Substring(0, 2)) name = strRecord.Substring(2) RecordCount = RecordCount + 1 txtOut.AppendText(name & ", " & CStr(age) & vbCrLf) Loop 'end of file has been reached txtOut.AppendText("You have " & CStr(RecordCount) & " friends.") End SubThe program opens the file and declares variables to hold the entire record and a count of the records. The loop processes the records one at a time until the end of file is reached. During each iteration of the loop, the Mid function is used to separate the record into its name and age fields, a line of output is displayed and the record counter is incremented by 1.
This file had fixed format records with fields in specific columns. Alternatively, it could have been a delimited text file like this one:
55,George Washington 50,Martha Washington 8,Abraham Lincoln 8,Mary Lincoln 9,John F. Kennedy 7,Jacqueline Kennedy 42,Dwight D. Eisenhower 47,Mamie Eisenhower 60,Harry Truman 65,Bess TrumanIn this file, the fields are separated by a delimiter character. The delimiter in this example is a comma, but any character could have been used as long as it would never appear in a field value.
With a delimited file, parsing a record into its constituent fields is a little more difficult than with fixed length fields. It could be done with the string methods or functions we have seen earlier or with the Split method of the String class. The Split method is designed for parsing delimited records. We have not yet looked at the Split method, but you can learn to use it by reading the Help files.