File access in COBOL is how you read and write records: in order (sequential), by key (random), or both (dynamic). The access mode you choose depends on the file organization and how you need to process the data. This page explains sequential, random, and dynamic access and when to use each.
| Access mode | Meaning |
|---|---|
| SEQUENTIAL | Records processed in order (start to end or from START position). Only mode for sequential files. |
| RANDOM | Access by key: set the key, then READ/WRITE/REWRITE/DELETE that record. For indexed and relative files. |
| DYNAMIC | Mix of both: access by key and READ NEXT (or PREVIOUS). For indexed and relative files only. |
With ACCESS MODE IS SEQUENTIAL you process records one after another. You OPEN the file, then READ repeatedly until end of file (or use START to position first). For sequential and line-sequential files this is the only option. For indexed or relative files, sequential access means reading in key order or relative record number order. Use it when you need to scan the whole file or from a given position to the end.
1234567891011121314SELECT CUST-FILE ASSIGN TO 'CUSTOMER.DAT' ORGANIZATION IS SEQUENTIAL ACCESS MODE IS SEQUENTIAL. *> Read every record in order OPEN INPUT CUST-FILE PERFORM UNTIL no-more READ CUST-FILE AT END SET no-more TO TRUE NOT AT END PERFORM PROCESS-RECORD END-READ END-PERFORM CLOSE CUST-FILE
With ACCESS MODE IS RANDOM you go directly to a record by key. For an indexed file you move the key value to the record key field, then READ (or WRITE/REWRITE/DELETE). For a relative file you set the relative key (record number) and then READ or WRITE. You do not read through previous records. Use random access when you need to look up or update a specific record by ID or key.
12345678*> Indexed file: read record with primary key = WS-KEY MOVE WS-KEY TO CUST-ID READ CUST-FILE INVALID KEY DISPLAY 'Not found' NOT INVALID KEY PERFORM PROCESS-RECORD END-READ
With ACCESS MODE IS DYNAMIC you can do both. For example: READ by key to find a record, then READ NEXT to get the following records in key order. Or use START to position at a key, then READ NEXT in a loop. Only indexed and relative files support dynamic access. Use it when you need to jump to a key and then scan forward (or backward with READ PREVIOUS where supported).
Sequential / line-sequential: SEQUENTIAL only. Indexed: SEQUENTIAL, RANDOM, or DYNAMIC. Relative: SEQUENTIAL, RANDOM, or DYNAMIC. Choose the organization (and key design) first; then choose the access mode that matches how you will read and update the file.
Sequential is like reading a book from page 1 to the end. Random is like opening the book to one page number you know. Dynamic is like opening to a page, then turning pages one by one from there. The kind of “book” (file organization) decides which of these you can do.
1. Which access mode lets you read a record by key and then read the next record in key order?
2. Sequential files support which access mode(s)?