Monday, 28 July 2014

COBOL File Operations: OPEN, READ, WRITE, and REWRITE

OPEN INPUT CUST-FILE establishes how a COBOL program can use a file; the next READ either returns a record or sets an end/error condition. Each later operation must match the file organization, access mode, and OPEN mode declared for that file.

COBOL file operations from OPEN through READ WRITE REWRITE DELETE and CLOSE with FILE STATUS checks
Open the file, perform the permitted record operation, check status, and close it.

What are COBOL file operations?

COBOL file operations are the statements that connect a logical COBOL file to an external data set and process its records. The core statements are OPEN, READ, WRITE, REWRITE, DELETE, START, and CLOSE. The valid statements depend on whether the file is sequential, indexed, or relative and whether it is open for input, output, update, or extension.

This page is the lifecycle overview. Use the COBOL file organizations guide for organization selection and the COBOL file I/O modes guide for detailed OPEN-mode rules.

The four parts of a COBOL file definition

  1. SELECT entry: associates the program file-name with an external assignment name and declares organization, access, keys, and FILE STATUS.
  2. FD entry: describes the logical record layout used by the program.
  3. Procedure Division statements: open the file and read, add, replace, delete, position, or close records.
  4. Runtime allocation: a JCL DD statement or site runtime mapping identifies the physical z/OS data set.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
    SELECT CUST-FILE ASSIGN TO CUSTIN
        ORGANIZATION IS SEQUENTIAL
        ACCESS MODE IS SEQUENTIAL
        FILE STATUS IS WS-CUST-STATUS.

DATA DIVISION.
FILE SECTION.
FD  CUST-FILE
    RECORD CONTAINS 80 CHARACTERS.
01  CUST-RECORD                  PIC X(80).

WORKING-STORAGE SECTION.
01  WS-CUST-STATUS               PIC XX.
One status field per file: IBM recommends checking the two-character FILE STATUS value after every input/output request. A value of 00 means the operation completed normally; other values describe end-of-file, key, allocation, attribute, or logic conditions.

COBOL file operation and OPEN mode matrix

OperationPurposeTypical required OPEN modeFile notes
READRetrieve a recordINPUT or I-OSequential, indexed, and relative files
WRITEAdd a new recordOUTPUT, EXTEND, or supported I-O useRules vary by organization and access mode
REWRITEReplace an existing recordI-OSequential access normally requires a successful READ first
DELETERemove a recordI-OIndexed and relative files only
STARTPosition for later sequential retrievalINPUT or I-OIndexed and relative files with sequential or dynamic access
CLOSEEnd file processingThe file must be openApplies to every organization

OPEN and CLOSE establish the processing window

OPEN INPUT permits reading, OPEN OUTPUT prepares a file for new output, OPEN I-O permits supported read/update activity, and OPEN EXTEND adds records after existing sequential data. The focused COBOL OPEN statement tutorial covers each form.

OPEN INPUT  CUST-FILE
     OUTPUT REPORT-FILE

IF WS-CUST-STATUS NOT = "00"
    DISPLAY "CUST-FILE OPEN FAILED: " WS-CUST-STATUS
END-IF

...

CLOSE CUST-FILE REPORT-FILE

Do not continue processing after a failed OPEN. For example, status 35 can indicate an unavailable nonoptional file, while status 39 indicates that fixed data-set attributes conflict with the COBOL definition.

READ retrieves sequential or keyed records

A sequential READ advances to the next logical record. Use AT END to stop a loop cleanly. An indexed or relative file with random or dynamic access can use a key to retrieve a particular record. See the dedicated COBOL READ statement guide for additional forms.

READ CUST-FILE
    AT END
        SET END-OF-CUST TO TRUE
    NOT AT END
        PERFORM PROCESS-CUSTOMER
END-READ

Status 10 is the normal end-of-file condition for a sequential READ. It is not a damaged-file code. Handle it as the end of the input stream rather than reporting an application failure.

WRITE adds a new logical record

WRITE names the record description, not the file-name. Populate the output record, then write it. For a keyed file, a duplicate prime key commonly produces status 22.

MOVE CUST-RECORD TO REPORT-RECORD
WRITE REPORT-RECORD
IF WS-REPORT-STATUS NOT = "00"
    DISPLAY "REPORT WRITE FAILED: " WS-REPORT-STATUS
END-IF

The COBOL sequential file example shows READ, WRITE, and end-of-file control together.

REWRITE replaces an existing record

Open the file in I-O mode before REWRITE. With sequential access, the record to replace must normally be established by a successful READ, and the program must not disturb the prime key before rewriting an indexed record. A missing qualifying READ can produce status 43.

READ CUSTOMER-MASTER
    INVALID KEY
        DISPLAY "CUSTOMER NOT FOUND: " WS-CUST-STATUS
    NOT INVALID KEY
        MOVE NEW-ADDRESS TO CUST-ADDRESS
        REWRITE CUSTOMER-RECORD
            INVALID KEY
                DISPLAY "REWRITE FAILED: " WS-CUST-STATUS
        END-REWRITE
END-READ

DELETE removes indexed or relative records

Enterprise COBOL DELETE removes a record from an indexed or relative file that is open in I-O mode. It does not delete a QSAM sequential record. A sequential data set is normally changed by reading the original and writing the records to retain into a replacement data set.

With sequential access, a successful READ must establish the record before DELETE. With random or dynamic access, supply the record key or relative key before issuing DELETE. The COBOL DELETE statement guide provides focused examples.

MOVE WS-CUSTOMER-ID TO CUST-ID
DELETE CUSTOMER-MASTER RECORD
    INVALID KEY
        DISPLAY "DELETE FAILED: " WS-CUST-STATUS
END-DELETE

START positions an indexed or relative file

START does not return a record. It positions an indexed or relative file so a later sequential READ can retrieve a qualifying record. The file must be open in INPUT or I-O mode and use sequential or dynamic access.

MOVE "C10000" TO CUST-ID
START CUSTOMER-MASTER
    KEY IS NOT LESS THAN CUST-ID
    INVALID KEY
        DISPLAY "NO STARTING KEY: " WS-CUST-STATUS
END-START

After a successful START, issue READ ... NEXT RECORD. Review the COBOL START statement guide and the COBOL indexed file tutorial for keyed processing details.

Complete sequential file copy example

IDENTIFICATION DIVISION.
PROGRAM-ID. COPYCUST.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
    SELECT INPUT-FILE  ASSIGN TO CUSTIN
        ORGANIZATION IS SEQUENTIAL
        FILE STATUS IS WS-IN-STATUS.
    SELECT OUTPUT-FILE ASSIGN TO CUSTOUT
        ORGANIZATION IS SEQUENTIAL
        FILE STATUS IS WS-OUT-STATUS.

DATA DIVISION.
FILE SECTION.
FD  INPUT-FILE RECORD CONTAINS 80 CHARACTERS.
01  INPUT-RECORD                 PIC X(80).
FD  OUTPUT-FILE RECORD CONTAINS 80 CHARACTERS.
01  OUTPUT-RECORD                PIC X(80).

WORKING-STORAGE SECTION.
01  WS-IN-STATUS                 PIC XX.
01  WS-OUT-STATUS                PIC XX.
01  WS-END                       PIC X VALUE "N".
    88 END-OF-INPUT              VALUE "Y".

PROCEDURE DIVISION.
    OPEN INPUT INPUT-FILE
         OUTPUT OUTPUT-FILE

    IF WS-IN-STATUS NOT = "00"
        DISPLAY "INPUT OPEN FAILED: " WS-IN-STATUS
        STOP RUN
    END-IF
    IF WS-OUT-STATUS NOT = "00"
        DISPLAY "OUTPUT OPEN FAILED: " WS-OUT-STATUS
        CLOSE INPUT-FILE
        STOP RUN
    END-IF

    PERFORM UNTIL END-OF-INPUT
        READ INPUT-FILE
            AT END
                SET END-OF-INPUT TO TRUE
            NOT AT END
                MOVE INPUT-RECORD TO OUTPUT-RECORD
                WRITE OUTPUT-RECORD
                IF WS-OUT-STATUS NOT = "00"
                    DISPLAY "WRITE FAILED: " WS-OUT-STATUS
                    SET END-OF-INPUT TO TRUE
                END-IF
        END-READ
    END-PERFORM

    CLOSE INPUT-FILE OUTPUT-FILE
    STOP RUN.

Matching JCL DD statements

//COPYSTEP EXEC PGM=COPYCUST
//STEPLIB  DD  DSN=USER01.LOADLIB,DISP=SHR
//CUSTIN   DD  DSN=USER01.CUSTOMER.INPUT,DISP=SHR
//CUSTOUT  DD  DSN=USER01.CUSTOMER.OUTPUT,
//             DISP=(NEW,CATLG,DELETE),
//             UNIT=SYSDA,SPACE=(CYL,(2,1)),
//             DCB=(RECFM=FB,LRECL=80,BLKSIZE=0)
//SYSOUT   DD  SYSOUT=*

The assignment names CUSTIN and CUSTOUT match the JCL ddnames in this common z/OS setup. Confirm the naming convention and runtime options used at your site.

File status codes worth checking first

StatusTypical meaningFirst check
00Successful operationContinue processing
10End of sequential inputEnd the read loop normally
22Duplicate key or key sequence conditionCheck the key and access method
23Requested keyed record not foundCheck the key value
35Nonoptional file unavailableCheck the DD statement and data-set name
39Fixed file attributes conflictCompare organization, keys, record type, and record size
41OPEN attempted on an already open fileReview control flow
43Required prior READ is missingReview sequential REWRITE or DELETE logic
47READ attempted in an invalid OPEN modeUse INPUT or I-O
48WRITE attempted in an invalid OPEN modeReview OUTPUT, EXTEND, or supported I-O use
49DELETE or REWRITE attempted outside I-O modeOpen the file I-O

File status meanings can depend on organization and operation. Use the COBOL file status codes guide before treating a code as a generic failure.

Common COBOL file-operation mistakes

  • Wrong OPEN mode: READ, WRITE, REWRITE, or DELETE does not match the active mode.
  • Unchecked status: the program continues after OPEN or WRITE failed.
  • Missing end handling: status 10 is treated as an error or the loop attempts another invalid READ.
  • Writing the file-name: WRITE must name a record description such as OUTPUT-RECORD.
  • Rewriting without a qualifying READ: sequential update logic loses the current-record position.
  • Deleting from a sequential file: DELETE is valid for indexed and relative organization, not QSAM sequential files.
  • DD/record mismatch: LRECL, record format, organization, or keys do not agree with the program.
Production check: stop or route control deliberately after a failed OPEN, WRITE, REWRITE, or DELETE. A displayed status code is useful only if the program avoids processing invalid record contents afterward.

COBOL file-operation checklist

  1. Choose the organization and access mode from the required record-processing pattern.
  2. Match SELECT, FD, record length, key definitions, and JCL allocation.
  3. Use an OPEN mode that permits every planned statement.
  4. Check FILE STATUS after every operation and handle end-of-file separately.
  5. Close every successfully opened file on normal and controlled-error paths.

Official IBM references

COBOL file operations FAQ

What are the main COBOL file operations?

OPEN establishes the processing mode, READ retrieves a record, WRITE adds a record, REWRITE replaces a record, DELETE removes a keyed record, START positions a keyed file, and CLOSE ends the connection to the file.

What is the difference between WRITE and REWRITE in COBOL?

WRITE adds a new logical record. REWRITE replaces an existing record and normally requires the file to be open in I-O mode; sequential access also requires a successful READ before the REWRITE.

Can COBOL DELETE a record from a sequential file?

No. Enterprise COBOL DELETE applies to indexed and relative files. A sequential data set is normally changed by writing a replacement data set.

What does COBOL file status 39 mean?

File status 39 means OPEN found a conflict between fixed file attributes and the COBOL definition, such as organization, record keys, record size, record type, or blocking information.

The safest file-handling routine treats OPEN mode, record position, and FILE STATUS as one unit; changing any one of them can change which operation is valid next.

No comments:

Post a Comment

New In-feed ads