Variable-length records are file records that can be different lengths (within a range). In COBOL you define them in the FD with RECORD IS VARYING FROM min TO max CHARACTERS DEPENDING ON length-field. After a READ, the length-field holds the length of the record just read; before a WRITE, you set the length-field to how many characters to write. This page explains the syntax and how to read and write variable records.
In the FILE SECTION, the FD must specify the range of lengths and the data item that will hold the actual length. That item must be an unsigned integer (e.g. PIC 9(4)). It can be in the record description or in WORKING-STORAGE; the run time sets it on READ and uses it on WRITE.
| Clause / phrase | Meaning |
|---|---|
| RECORD IS VARYING | Declares the file has variable-length records |
| FROM min TO max CHARACTERS | Minimum and maximum record length in characters |
| DEPENDING ON identifier | Data item that holds actual length (after READ; set before WRITE) |
12345678910FILE SECTION. FD VAR-FILE RECORD IS VARYING FROM 1 TO 2000 CHARACTERS DEPENDING ON WS-REC-LEN. 01 VAR-RECORD. 05 VAR-DATA PIC X(2000). *> WS-REC-LEN in WORKING-STORAGE: PIC 9(4) or similar WORKING-STORAGE SECTION. 01 WS-REC-LEN PIC 9(4).
FROM 1 TO 2000 means each record has between 1 and 2000 characters. DEPENDING ON WS-REC-LEN means after a READ, WS-REC-LEN contains the actual length; before a WRITE, you set WS-REC-LEN to the length you are writing. The record area VAR-DATA is 2000 bytes so it can hold the maximum-length record.
Use a normal READ file-name (or READ into a record). After a successful READ, the DEPENDING ON field is set to the length of the record just read. Only that many bytes of the record area are defined; bytes beyond that are undefined. Use the length when processing (e.g. when moving or inspecting only the valid portion).
12345678910READ VAR-FILE AT END SET WS-EOF TO TRUE NOT AT END *> WS-REC-LEN now has the length of the record read PERFORM PROCESS-RECORD END-READ. PROCESS-RECORD. *> Process only VAR-DATA (1:WS-REC-LEN) or use WS-REC-LEN in logic ...
Set the DEPENDING ON field to the number of characters you want to write, then WRITE the record. The run time writes only that many characters. The record area should be at least as long as that value. Typically you build the data in the record area, set the length field to the actual used length, then WRITE.
12345*> Build data in VAR-DATA, then set length and write MOVE "some data" TO VAR-DATA MOVE 9 TO WS-REC-LEN WRITE VAR-RECORD. *> Writes 9 characters
1. After READ on a variable-length file, where is the record length?
2. Before WRITE of a variable-length record, what must you do?