Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 38 ยท File Handling

Sequential Files

Learn COBOL sequential file processing - SELECT and ASSIGN, FD record layouts, OPEN, READ, WRITE, CLOSE, the read-ahead loop, fixed and variable records, and the classic copy and merge patterns.

COBOL was built for batch processing: read a file of records, do something with each one, write a file of results. The sequential file is the simplest and most common kind. Records are read in the order they were written, from first to last, like lines in a text file or cards in a deck. Almost every COBOL job you will meet is a variation of "read a sequential file, process, write a sequential file".

This lesson walks through all four parts you need: describing the file in the Environment Division, describing its records in the Data Division, and opening, reading, writing and closing it in the Procedure Division.

The four pieces

A file touches three divisions. Here is a complete program that copies customers with a balance over 1,000 into a new file:

COBOL
       IDENTIFICATION DIVISION.
       PROGRAM-ID. BIGCUST.
       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
           SELECT CUST-IN  ASSIGN TO "customers.dat"
               ORGANIZATION IS LINE SEQUENTIAL.
           SELECT CUST-OUT ASSIGN TO "bigcust.dat"
               ORGANIZATION IS LINE SEQUENTIAL.
       DATA DIVISION.
       FILE SECTION.
       FD  CUST-IN.
       01  CUST-IN-REC.
           05  CI-ID       PIC 9(5).
           05  CI-NAME     PIC X(20).
           05  CI-BALANCE  PIC 9(6)V99.
       FD  CUST-OUT.
       01  CUST-OUT-REC    PIC X(33).
       WORKING-STORAGE SECTION.
       01  WS-EOF          PIC X VALUE "N".
           88  AT-EOF      VALUE "Y".
       PROCEDURE DIVISION.
       MAIN.
           OPEN INPUT CUST-IN
                OUTPUT CUST-OUT
           READ CUST-IN
               AT END SET AT-EOF TO TRUE
           END-READ
           PERFORM UNTIL AT-EOF
               IF CI-BALANCE > 1000
                   WRITE CUST-OUT-REC FROM CUST-IN-REC
               END-IF
               READ CUST-IN
                   AT END SET AT-EOF TO TRUE
               END-READ
           END-PERFORM
           CLOSE CUST-IN CUST-OUT
           STOP RUN.

Take it apart:

  • SELECT ... ASSIGN TO links the program's name for the file (CUST-IN) to something outside: a path in GnuCOBOL, a DD name in JCL on a mainframe (ASSIGN TO CUSTIN, see JCL for COBOL jobs).
  • ORGANIZATION IS SEQUENTIAL means fixed-format binary records; LINE SEQUENTIAL (GnuCOBOL and several other compilers) means text lines ended by a newline. IBM mainframe COBOL has no LINE SEQUENTIAL; records are fixed or variable blocks.
  • FD (file description) in the File Section names the file and has a record description beneath. Every SELECT needs a matching FD.
  • The record is a normal data description. Several 01 levels under one FD redefine the same buffer.
flowchart LR
    D["Disk file<br/>customers.dat"] -->|"READ"| B["FD buffer<br/>CUST-IN-REC"]
    B -->|"MOVE or WRITE FROM"| W["FD buffer<br/>CUST-OUT-REC"]
    W -->|"WRITE"| O["Disk file<br/>bigcust.dat"]

The FD record area is a buffer: READ fills it, WRITE sends it.

OPEN and CLOSE

OPEN chooses the direction. The common modes:

Mode Meaning
INPUT Read only; the file must exist
OUTPUT Write; creates the file or replaces an existing one
EXTEND Write at the end, keeping existing records
I-O Read and rewrite records in place (REWRITE)

CLOSE releases the file and flushes buffered data. A file you forget to close may lose its last records. STOP RUN closes open files on most compilers, but do not rely on it.

OPEN OUTPUT empties an existing file. If you meant to add records, use OPEN EXTEND.

READ and the read-ahead loop

READ file copies the next record into the buffer. At the end of the file the AT END branch runs. A subtle point: after end-of-file you must not read again.

The standard pattern is read ahead: read once before the loop, process, and read again at the bottom of the loop. The test at the top then sees the result of the last read. It avoids processing the last record twice, which is the typical bug of the "test at the bottom" approach.

COBOL
           READ CUST-IN AT END SET AT-EOF TO TRUE END-READ
           PERFORM UNTIL AT-EOF
               PERFORM PROCESS-RECORD
               READ CUST-IN AT END SET AT-EOF TO TRUE END-READ
           END-PERFORM

READ file INTO ws-item also moves the record to a working-storage copy, which is useful when you must keep the record after the next READ. A NOT AT END branch can hold the processing instead of the loop body, but read-ahead stays the most readable.

WRITE

WRITE takes the record name, not the file name: WRITE CUST-OUT-REC. WRITE rec FROM ws-item moves from a working-storage item first. Remember to build the whole record, because leftover bytes from a previous WRITE stay in the buffer. A safe habit is MOVE SPACES TO OUT-REC before assembling a record.

For printed reports WRITE rec AFTER ADVANCING 2 LINES controls spacing; a LINAGE clause and AFTER ADVANCING PAGE handle page breaks.

Fixed, variable and blocked records

  • Fixed: all records are the same length (the usual case).
  • Variable: records have different lengths; the FD can say RECORD VARYING FROM 10 TO 200 DEPENDING ON REC-LEN, and REC-LEN holds the length after a READ or before a WRITE. Tables with OCCURS DEPENDING ON often produce these (variable-length tables).
  • Blocked: many logical records are stored in one physical block to save space and I/O (BLOCK CONTAINS n RECORDS; on the mainframe it is normally BLOCK CONTAINS 0 and the JCL or dataset decides). You do not see blocks in the program; the runtime unpacks them.

Practicing without a COBOL runtime

The Python blocks below are labelled models of the programs above: they use fixed-width text records, Decimal, and the same read-ahead structure.

Python Stand-in: fixed-width records, filter and copy (BIGCUST)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Stand-in: control totals while reading a file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Both blocks show the same record layout: 33 characters per record. The first prints the two matching records (balances 1500.00 and 1000.01). The second prints records read: 3 and balance total: 3500.00. Control totals like these are how batch programs prove that nothing was lost.

Common mistakes

  1. Reading again after end of file (leads to file status 46).
  2. WRITE with the file name instead of the record name.
  3. Opening a file twice without a CLOSE in between.
  4. A record description whose length does not match the real file: fields shift and numbers become garbage. On a mainframe, compare with the dataset's LRECL.
  5. Ignoring errors. Every file should have a status field, as the next lesson shows: file status and error handling.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which OPEN mode keeps existing records and adds new ones at the end?

    EXTEND positions the file at its end. OUTPUT would replace the content.
  2. 2. What name do you give to WRITE?

    You READ a file but WRITE a record. WRITE rec FROM ws-item moves data first.
  3. 3. Why does the read-ahead pattern read once before the loop?

    The loop body processes a record already read; the next READ at the bottom decides whether to continue.
  4. 4. What does SELECT ... ASSIGN TO connect?

    ASSIGN is the bridge to the outside world; on z/OS it names a DD statement.

Summary

  • A file needs SELECT/ASSIGN (Environment), FD and a record (Data) and OPEN/READ/WRITE/CLOSE (Procedure).
  • Use OPEN INPUT, OUTPUT, EXTEND or I-O deliberately; OUTPUT erases.
  • Read ahead: first READ before the loop, next READ at the bottom.
  • WRITE uses the record name; clear or fully build the record first.
  • Compute control totals to prove a run is complete.

Next: File status and error handling