Random Access Files



Random files are record-based files with an internal structure that supports "direct access" by record number. This means that your program can read from or write to a specific record in a random access file, say the 50th record, without reading through the previous 49 records. Compare that to reading or writing a sequential file, where to get to a specific record, you must read through all preceding records.

The difference between random access and sequential access can be likened to accessing music on a CD versus a cassette tape. To get to song number 6, you can tell your CD player to go directly to track 6, whereas on a cassette tape, you must fast-forward through the first 5 songs to get to song number 6.

There are Three statement of Random Access Files : 
  1. Open Statement
  2. Get Statement
  3. Put Statement


The Open Statement for Random Access Files

The "full blown" syntax for the Open statement was given in the previous topic on binary files. The syntax for the Open statement, as it pertains to random files, is as follows:

1) If you only want to read from the random access file, use:

      Open filename For Random Access Read As #filenumber Len = reclength

2) and if you only want to write to the random access file, use:

      Open filename For Random Access Write As #filenumber Len = reclength

3) and if you want to both read from and write to the random access file (for example, you want to access a      
    particular record and then update one or more of its fields), use:

       Open filename For Random Access Read Write As #filenumber Len = reclength

Note : reclength refers to the total length in bytes. 



The Get Statement

The Get statement is used read data from a file opened in random mode. The syntax, as it applies to random files is:

Get [#]filenumber, [recnumber], varname

Note : Recnumber is the record position within the file that is read.


The Put Statement

The Put statement is used write data to a file opened in random mode. The syntax, as it applies to binary files is:

Put [#]filenumber, [recnumber], varname

Note : Recnumber is the record position within the file that is read.