COBOL by Example: Relative Files
Understanding relative file organization for record access by position number, using RELATIVE KEY with Working-Storage variables, implementing array-like disk storage, and managing sparse data efficiently.
Code
IDENTIFICATION DIVISION.
PROGRAM-ID. REL-FILES.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT DATA-FILE ASSIGN TO "data.dat"
ORGANIZATION IS RELATIVE
ACCESS MODE IS RANDOM
RELATIVE KEY IS REC-NUM.
DATA DIVISION.
FILE SECTION.
FD DATA-FILE.
01 DATA-REC PIC X(20).
WORKING-STORAGE SECTION.
01 REC-NUM PIC 99.
PROCEDURE DIVISION.
OPEN INPUT DATA-FILE.
MOVE 5 TO REC-NUM.
READ DATA-FILE
INVALID KEY DISPLAY "Record 5 empty"
NOT INVALID KEY DISPLAY "Rec 5: " DATA-REC
END-READ.
CLOSE DATA-FILE.
STOP RUN.Explanation
Relative files are similar to arrays but stored on disk. Records are accessed by their relative position (Record 1, Record 2, etc.). This is faster than indexed files because no index lookup is required; the system calculates the offset directly based on the record length.
You define a RELATIVE KEY variable in Working-Storage (not in the file record itself) to specify which record number you want to read or write. This key acts as the "array index" for the file.
Relative files are ideal for data that is naturally numbered, such as days of the year (1-366) or sequential invoice numbers. However, they can be wasteful of space if the data is sparse (e.g., if you have record 1 and record 1000, space is reserved for the 998 empty slots in between).

