Reading records from a file

Use the READ statement to retrieve records from a file. To read a record, you must have opened the file with OPEN INPUT or OPEN I-O (OPEN I-O is not valid for line-sequential files). Check the file status key after each READ.

About this task

You can retrieve records in sequential and line-sequential files only in the sequence in which they were written.

You can retrieve records in indexed and relative record files sequentially (according to the ascending order of the key for indexed files, or according to ascending relative record locations for relative files), randomly, or dynamically.

When using dynamic access, you can switch between reading records sequentially and reading a specific record directly. For sequential retrieval, code READ NEXT and READ PREVIOUS; and for random retrieval (by key), use READ.

To read sequentially beginning at a specific record, use a START statement to set the file position indicator to point to a particular record before the READ NEXT or the READ PREVIOUS statement. If you code START followed by READ NEXT, the next record is read, and the file position indicator is reset to the next record. If you code START followed by READ PREVIOUS, the previous record is read, and the file position indicator is reset to the previous record. You can move the file position indicator randomly by using START, but all reading is done sequentially from that point.

You can continue to read records sequentially, or you can use START to move the file position indicator. For example:


START file-name KEY IS EQUAL TO ALTERNATE-RECORD-KEY

If a direct READ is performed for an indexed file based on an alternate index for which duplicates exist, only the first record in the file (base cluster) with that alternate key value is retrieved. You need a series of READ NEXT statements to retrieve each of the records that have the same alternate key. A file status value of 02 is returned if there are more records with the same alternate key value still to be read. A value of 00 is returned when the last record with that key value has been read.

Related tasks  
Opening a file  
Using file status keys

Related references  
File position indicator  
FILE STATUS clause (COBOL for Linux® on x86 Language Reference)