RANDOM ACCESS FILES
In the sequential reading example, after reading nine lines, the next read operation would start at the beginning of the 10th line. The file read point was positioned at the 10th line. That position could be described with an integer as the nth byte in the file, where the first byte in the file is at position zero, similar to the first element of an array is in position zero.
When reading and writing with random access, you must know exactly where the
data starts in the file. One way to do this is to use the same record size every time. In the
following pseudocode for a subroutine to read a record, the variable
recordBuffer is an array of characters that has a fixed size so
you can calculate where to read.
FUNCTION readCheck( chkNum, recordBuffer ) OPEN "checks.dat" FOR RANDOM AS #ranf SEEK #ranf TO chkNum * checkRecordSize READ #ranf recordBuffer CLOSE #ranf RETURN
In another part of the program, there would have to be routines that pick the
characters out of the recordBuffer and then interpret them in
terms of your check records.
Using random access becomes increasingly helpful as files get larger. Just think how much harder it'd be to read the last 100 bytes in a 10 megabyte file by sequential reading instead of seeking a file position equal to the size of the file minus 100.
Database technology absolutely depends on random access because the files are so large, but is limited by the fact that after you've decided on a record size for a file, you can't change it. If your record design changes, you have to write a program that can read all of the old records and write a new file with the new record sizes.
Moving On
This lesson covered the important programming concepts of data storage, file manipulation, and memory management. You should now be able to more easily solve real-world programming problems. You also learned some important data storage technology terms.
The next lesson looks at an aspect of modern computing that is related to the data storage and retrieval techniques you saw in this lesson. Instead of reading and writing data on a local computer, you talk to other computers on local networks or the Internet. Before you move on, be sure to complete the assignment and quiz for this lesson. Don't forget to drop by the Message Board to see what your fellow students have to say.
