• We look at writing and reading random access files using a user-defined
variable. For other variable types, refer to Visual Basic on-line help. To open
a random access file named RanFileName, use:
Open RanFileName For Random As #N Len = RecordLength
where N is an available file number and RecordLength is the length of each
record. Note you don’t have to specify an input or output mode. With random
access files, as long as they’re open, you can write or read to them.
• To close a random access file, use:
Close N
• As mentioned previously, the record length is the sum of the lengths
of all variables that make up a record. A problem arises with String type variables.
You don’t know their lengths ahead of time. To solve this problem, Visual
Basic lets you declare fixed lengths for strings. This allows you to determine
record length. If we have a string variable named StrExample we want to limit
to 14 characters, we use the declaration:
Dim StrExample As String * 14
Recall each character in a string uses 1 byte, so the length of such a variable
is 14 bytes.
• Recall our example user-defined variable type, Person. Let’s
revisit it, now with restricted string lengths:
Type Person
Name As String * 40
City As String * 35
Height As Integer
Weight As Integer
End Type
The record length for this variable type is 79 bytes (40 + 35 +2 + 2). To open
a file named PersonData as File #1, with such records, we would use the statement:
Open PersonData For Random As #1 Len = 79
• The Get and Put statements are used to read from and write to random
access files, respectively. These statements read or write one record at a time.
The syntax for these statements is simple:
Get #N, [RecordNumber], variable
Put #N, [RecordNumber], variable
The Get statement reads from the file and stores data in the variable, whereas
the Put statement writes the contents of the specified variable to the file. In
each case, you can optionally specifiy the record number. If you do not specify
a record number, the next sequential position is used.
• The variable argument in the Get and Put statements is usually a single
user-defined variable. Once read in, you obtain the component parts of this variable
using dot-notation. Prior to writing a user-defined variable to a random access
file, you ‘load’ the component parts using the same dot-notation.
• There’s a lot more to using random access files; we’ve
only looked at the basics. Refer to your Visual Basic documentation and on-line
help for further information. In particular, you need to do a little cute programming
when deleting records from a random access file or when ‘resorting’
records.