REWRITE, DELETE, and EXTEND
In order to ammend a record in a file, such as to update
data (see League Table Program
in sample programs section), to delete a record altogther, or to add a record to
the end of a file, you can use REWRITE, DELETE or EXTEND,
respectively.
A D V E R T I S E M E N T
However, to use REWRITE or DELETE you must open the file using I-O
mode. Also, DELETE can only be used on files with RELATIVE or INDEXED
organization (see example below).
RELATIVE and INDEXED files are discussed in the following
section
The format of the DELETE statement is:
DELETE filename
ON INVALID KEY
{statements}
NOT ON INVALID KEY
{statements}
END-DELETE
ON INVALID KEY means the record was not found, so
you might want to display an error message
e.g. DISPLAY 'RECORD NOT FOUND'
To REWRITE you can refer to the level 01 name to change
the record with the ammended field:
FD IN-FILE
01 RECORD-IN.
03 IN-NAME PIC X(20).
03 IN-ADDRESS PIC X(60).
PROCEDURE DIVISION.
MAIN-PARAGRAPH.
:
OPEN I-O IN-FILE
:
READ IN-FILE
IF IN-NAME = 'BILLY NOMATES' THEN
MOVE 'JIMMY MOREPALS' TO IN-NAME
REWRITE RECORD-IN
ELSE
DISPLAY IN-NAME
END-IF
:
To EXTEND you must open the file in EXTEND mode:
OPEN EXTEND IN-FILE
:
DISPLAY 'Type in new name'
ACCEPT NEW-NAME
MOVE NEW-NAME TO IN-NAME
EXTEND IN-FILE
DISPLAY 'Type in new address'
ACCEPT NEW-ADDRESS
MOVE NEW-ADDRESS TO IN-ADDRESS
EXTEND IN-FILE
:
Here is a sample program that deletes a record from an
INDEXED file using the DELETE statement, followed by deletion of a record that
does not use the DELETE statement but writes the whole file (less the record to
be deleted) to a temporary file. The program asks for a six digit code that
identifies the record to be removed from the file. If you want to try this
program then you'll need to create a couple of test files: TESTDATA1.DAT and
TESTDATA2.TXT.
TESTDATA1.DAT needs to be an indexed file. To create this
you'll need to compile and run the
Create INDEXED file program and
Read INDEXED file program (both in the Sample Code section).
TESTDATA2.TXT should be LINE SEQUENTIAL and of the form:
CODE--SOME ENTRY OF 43 CHARACTERS
123456abc----------**********----------**********
:
:
|