Menu
CoddyTech

The Read Loop

Part of the Files and Reports section of Coddy's COBOL Programming journey. Lesson 4 of 22.

A program cannot know how many records a file holds, so it reads in a loop until AT END. A flag with a condition name keeps track of the end:

01 WS-EOF PIC X VALUE "N".
    88 END-OF-FILE VALUE "Y".

The loop reads one record per pass. AT END sets the flag, and the work for a record goes in NOT AT END:

PERFORM UNTIL END-OF-FILE
    READ ORDER-FILE
        AT END SET END-OF-FILE TO TRUE
        NOT AT END PERFORM SHOW-ORDER
    END-READ
END-PERFORM.

Work placed after END-READ also runs on the last pass, when the READ found nothing. The record area still holds the last record, so it is processed twice.

This loop reads a file of any size, from no records to millions. Batch programs are built around it.

challenge icon

Challenge

Easy

Write the read loop in MAIN-PARA: read CUST-FILE until END-OF-FILE, and perform SHOW-CUSTOMER for each record, so every customer prints as C001 Ann Lee.

Try it yourself

       IDENTIFICATION DIVISION.
       PROGRAM-ID. READLP.
       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
           SELECT CUST-FILE ASSIGN TO CUSTIN
               ORGANIZATION IS LINE SEQUENTIAL.
       DATA DIVISION.
       FILE SECTION.
       FD CUST-FILE.
       01 CUST-REC.
           05 CUST-ID PIC X(4).
           05 CUST-NAME PIC X(10).
           05 CUST-CITY PIC X(6).
           05 CUST-BAL PIC 9(5).
       WORKING-STORAGE SECTION.
       01 WS-EOF PIC X VALUE "N".
           88 END-OF-FILE VALUE "Y".
       PROCEDURE DIVISION.
       MAIN-PARA.
           OPEN INPUT CUST-FILE.
           *> Write the read loop here
           CLOSE CUST-FILE.
           STOP RUN.
       SHOW-CUSTOMER.
           DISPLAY CUST-ID " " CUST-NAME.

All lessons in Files and Reports