REWRITE and DELETE
Part of the Programs That Work Together section of Coddy's COBOL Programming journey. Lesson 11 of 16.
To change records, open the file for input and output at once:
OPEN I-O CUST-MASTREWRITE replaces a record with the record area's new content. Read the record first, change its fields, then rewrite it. The key field must not change:
READ CUST-MAST
SUBTRACT PAYMENT FROM CUST-BALANCE
REWRITE CUSTOMER-RECWRITE would not do: it adds a new record, and with a key that is already there it fails with status 22.
DELETE removes the record whose key is in the key field. With random or dynamic access it needs no read first; with sequential access it deletes the record read last.
MOVE 10003 TO CUST-ID
DELETE CUST-MAST RECORD
INVALID KEY DISPLAY "No customer"
END-DELETEChallenge
EasyEach line of KEYSIN is a customer id and a payment. DO-KEY reads the customer; where the comment is, subtract PAYMENT from CUST-BALANCE and rewrite the record, so the listing at the end shows the new balances: Ada Lovelace pays 1250 and keeps 0.50.
Try it yourself
IDENTIFICATION DIVISION.
PROGRAM-ID. PAYMENT.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT KEY-FILE ASSIGN TO KEYSIN
ORGANIZATION IS LINE SEQUENTIAL.
SELECT CUST-MAST ASSIGN TO CUSTMAST
ORGANIZATION IS INDEXED
ACCESS MODE IS DYNAMIC
RECORD KEY IS CUST-ID
FILE STATUS IS MAST-STATUS.
DATA DIVISION.
FILE SECTION.
FD KEY-FILE.
01 KEY-REC.
05 KEY-ID PIC 9(5).
05 PAYMENT PIC 9(5).
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".
01 SHOW-BAL PIC ZZ,ZZ9.99.
PROCEDURE DIVISION.
MAIN-LOGIC.
CALL "LOADMAST"
OPEN INPUT KEY-FILE
OPEN I-O CUST-MAST
PERFORM UNTIL END-OF-FILE
READ KEY-FILE
AT END SET END-OF-FILE TO TRUE
NOT AT END PERFORM DO-KEY
END-READ
END-PERFORM
PERFORM LIST-ALL
CLOSE KEY-FILE CUST-MAST
STOP RUN.
DO-KEY.
MOVE KEY-ID TO CUST-ID
READ CUST-MAST
INVALID KEY DISPLAY "No customer " CUST-ID
END-READ
IF MAST-STATUS = "00"
*> Update the balance and the file here
CONTINUE
END-IF.
LIST-ALL.
MOVE "N" TO EOF-FLAG
MOVE ZERO TO CUST-ID
START CUST-MAST KEY IS >= CUST-ID
PERFORM UNTIL END-OF-FILE
READ CUST-MAST NEXT RECORD
AT END SET END-OF-FILE TO TRUE
NOT AT END
MOVE CUST-BALANCE TO SHOW-BAL
DISPLAY CUST-NAME " " SHOW-BAL
END-READ
END-PERFORM.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.