Accessing Files Programmer's Guide (32650-90885)

130 Chapter9
Reading from a File
Sequential Access and Random Access
Sequential Access and Random Access
Two of the most frequently used methods of transferring data from a file to your program
are sequential access and random access.
When you use sequential access to read data from a file, you read data from the record
currently pointed to by the record pointer. You use the FREAD intrinsic to read data
sequentially from a disk file or device file. When you open a file with any form of Read
access specified in the
access type option
of HPFOPEN/FOPEN, the file is opened with the
record pointer set to the first record in the file. When you have accomplished the read
operation, the file system automatically sets the record pointer to point to the beginning of
the next record in the file. Both disk files and device files can be accessed with the FREAD
intrinsic. When you use random access to read data from a disk file, you read data from
any record in the file by specifying where you want the file system to set the record pointer
prior to the read operation. You use the FREADDIR intrinsic to randomly access records in a
disk file. You must specify in FREADDIR which record that you want to read from. The file
system sets the record pointer to the selected record, then transfers the data from the
record to your program's stack. When you have accomplished the read operation, the file
system automatically sets the record pointer to point to the beginning of the next record in
the file. Only disk files can be accessed with the FREADDIR intrinsic
The following examples illustrate the use of file system intrinsics to perform sequential
access reads and random access reads from a disk file.
Reading from a disk file using sequential access
Example 9-1 is an HP Pascal/iX code segment that uses the FREAD intrinsic to read records
sequentially from a disk file. Example 9-1 contains a loop construct, where records are
read sequentially from disk_file and written to the file new_file (both files opened
elsewhere by HPFOPEN/FOPEN calls). The files are both standard ASCII files with
fixed-record format, each record 256 bytes in length. When a logical end-of-file (EOF) is
reached, a condition code of CCG is returned by FREAD. The loop ends when FREAD
encounters the EOF and returns the CCG condition to the program.
Example 9-1. Reading from a Disk File Using Sequential Access
.
.
.
var
expected_length: shortint; {required by FREAD }
record : packed array [1..256] of char; {declare record type }
control_code : 0..65535; {required by FWRITE }
record_length : shortint; {expected record length}
end_of_file : boolean; {declare exit condition}
.
.
.
begin