Menu
CoddyTech

Indexed Files

Part of the Programs That Work Together section of Coddy's COBOL Programming journey. Lesson 8 of 16.

A sequential file is read from the start. An indexed file keeps its records by a key, so a program can go straight to customer 10004. On a mainframe this is a VSAM KSDS; GnuCOBOL stores it in a small database file.

The SELECT says the file is indexed and which field of its record is the key:

SELECT ACCT-FILE ASSIGN TO ACCTMAST
    ORGANIZATION IS INDEXED
    ACCESS MODE IS DYNAMIC
    RECORD KEY IS ACCT-NO
    FILE STATUS IS ACCT-STATUS.

ACCESS MODE says how the program reaches records: SEQUENTIAL in key order, RANDOM by key, DYNAMIC both. The key is a field of the file's record, here ACCT-NO.

OPEN OUTPUT creates the file and WRITE adds records, in any order with random access. Keys are unique: INVALID KEY runs when a key is already there, and the file status is 22.

WRITE CUSTOMER-REC
    INVALID KEY DISPLAY "Duplicate " CUST-ID
END-WRITE

A branch that should do nothing holds CONTINUE, the statement that does nothing: INVALID KEY CONTINUE skips a duplicate quietly.

challenge icon

Challenge

Easy

The program loads the text file CUSTIN into the indexed file CUSTMAST. Write its SELECT: CUST-MAST, assigned to CUSTMAST, indexed, random access, keyed on CUST-ID, with the status in MAST-STATUS.

Try it yourself

       IDENTIFICATION DIVISION.
       PROGRAM-ID. LOADER.
       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
           SELECT CUST-FILE ASSIGN TO CUSTIN
               ORGANIZATION IS LINE SEQUENTIAL.
           *> Select CUST-MAST here
       DATA DIVISION.
       FILE SECTION.
       FD CUST-FILE.
       01 CUST-LINE      PIC X(24).
       FD CUST-MAST.
           COPY CUSTREC.
       WORKING-STORAGE SECTION.
       01 MAST-STATUS    PIC XX.
       01 EOF-FLAG       PIC X VALUE "N".
           88 END-OF-FILE  VALUE "Y".
       PROCEDURE DIVISION.
       MAIN-LOGIC.
           OPEN INPUT CUST-FILE
           OPEN OUTPUT CUST-MAST
           PERFORM UNTIL END-OF-FILE
               READ CUST-FILE
                   AT END SET END-OF-FILE TO TRUE
                   NOT AT END PERFORM LOAD-ONE
               END-READ
           END-PERFORM
           CLOSE CUST-FILE CUST-MAST
           STOP RUN.
       LOAD-ONE.
           MOVE CUST-LINE TO CUSTOMER-REC
           WRITE CUSTOMER-REC
               INVALID KEY DISPLAY "Duplicate " CUST-ID
               NOT INVALID KEY DISPLAY "Added " CUST-ID
           END-WRITE.

All lessons in Programs That Work Together