Declaring Variables for Random File Access
Before your application opens a file for random access, it should declare all variables required to handle data from the file. This includes user-defined types, which correspond to records in the file, as well as standard types for other variables that hold data related to processing a random-access file.
Before opening a file for random access, define a structure that corresponds to the records the file contains or will contain. For example, a hypothetical Employee Records database might contain a user-defined data type called
Person as follows:
Structure Person Public ID As Integer Public MonthlySalary As Decimal Public LastReviewDate As Long <VBFixedString(15)> Public FirstName As String <VBFixedString(15)> Public LastName As String <VBFixedString(15)> Public Title As String <VBFixedString(150)> Public ReviewComments As String End Structure
Declaring Field Variables in a Structure Definition
Because all records in a random-access file must have the same length, it is often useful for string elements in a user-defined type to have a fixed length also. In the
Person type declaration above, for example,
LastName have a fixed length of 15 characters. To declare a fixed-length string, set its length with the VBFixedString attribute.
If the actual string contains fewer characters than the fixed length of the string element to which it is written, Visual Basic fills the trailing spaces in the record with blanks (character code 32). If the string is longer than the field size, Visual Basic truncates it. (If you use variable-length strings, the total size of any record stored with the FilePut Function or retrieved with the FileGet Function must not exceed the record length specified in the FileOpen Function).
After defining a structure that corresponds to a typical record, declare any other variables that your application needs to process a file opened for random access. The Employee Records database, for instance, declares
LastRecord variables, as follows:
' Declare a record variable. Public Employee As Person ' Track the current record. Public Position As Long ' Get the number of the last record in the file. Public LastRecord As Long
Opening Files for Random Access | Editing Files Opened for Random Access | Writing Variables to Records | File Access with Visual Basic Run-Time Functions | Sequential File Access | Binary File Access