Showing posts with label COBOL file handling. Show all posts
Showing posts with label COBOL file handling. Show all posts

Monday, 28 July 2014

COBOL File I/O Modes: INPUT, OUTPUT, I-O, and EXTEND

A batch job often fails before the first business rule runs because the file was opened in the wrong mode. A program that needs to read customer records should not use OPEN OUTPUT. A program that appends audit records should not recreate the file. In COBOL, the OPEN mode tells the runtime what the program plans to do with the file.

COBOL file I/O modes diagram showing INPUT OUTPUT I-O and EXTEND choices
Choose the mode first.

What are COBOL file I/O modes?

COBOL file I/O modes are the phrases used with the OPEN statement: INPUT, OUTPUT, I-O, and EXTEND. They decide which file statements are valid after the file is open. If the wrong mode is used, later READ, WRITE, REWRITE, or DELETE statements can fail or damage data.

OPEN INPUT  CUSTOMER-FILE
OPEN OUTPUT REPORT-FILE
OPEN I-O    MASTER-FILE
OPEN EXTEND AUDIT-FILE

Good file handling is simple: open the file in the mode that matches the next operation, check FILE STATUS, process the records, and close the file before the program ends.

Quick comparison

OPEN mode Use it when Common valid statements Main risk
INPUT The program only reads an existing file. READ Fails if a required file is missing.
OUTPUT The program creates a new file or replaces old records. WRITE Can clear existing records when used on the wrong file.
I-O The program reads records and updates them. READ, REWRITE, DELETE Can fail when the organization or access mode does not allow updates.
EXTEND The program appends new records after the last record. WRITE Fails for a missing non-optional file and is not valid for every file type.

OPEN INPUT: read an existing file

Use OPEN INPUT when the program reads records and does not change the file. A daily balance report, customer extract reader, or validation job usually opens the input file this way.

SELECT CUSTOMER-FILE ASSIGN TO CUSTIN
    FILE STATUS IS WS-CUST-STATUS.

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

If the required data set is missing, a typical status is 35. If the file is declared OPTIONAL, the open can succeed with a different status, so support teams should check the program's SELECT clause before assuming the JCL is wrong.

OPEN OUTPUT: create or replace records

Use OPEN OUTPUT for a new output file, such as a report, extract, or unload file. Be careful with existing files. On many jobs, opening an existing file for output means the old contents are replaced by new data.

SELECT REPORT-FILE ASSIGN TO REPTDD
    FILE STATUS IS WS-REPT-STATUS.

OPEN OUTPUT REPORT-FILE
IF WS-REPT-STATUS = "00"
   WRITE REPORT-REC
ELSE
   DISPLAY "REPORT OPEN FAILED: " WS-REPT-STATUS
END-IF

This is the mode that deserves the most review in production changes. A wrong DD name or copied program can point OPEN OUTPUT at a valuable file and replace records that were meant to be kept.

OPEN I-O: read and update records

Use OPEN I-O when the same file is read and changed. A VSAM KSDS maintenance program may read a customer master record, change a field, and then issue REWRITE. A delete program may read a key and then issue DELETE.

OPEN I-O CUSTOMER-MASTER
IF WS-MASTER-STATUS NOT = "00"
   DISPLAY "MASTER OPEN FAILED: " WS-MASTER-STATUS
   GOBACK
END-IF

READ CUSTOMER-MASTER
   INVALID KEY DISPLAY "CUSTOMER NOT FOUND"
END-READ

REWRITE CUSTOMER-MASTER-REC
   INVALID KEY DISPLAY "REWRITE FAILED"
END-REWRITE

I-O is not a shortcut for every file. The file organization, access mode, and data set allocation must support update processing. If a file is sequential and the program only needs to append new rows, EXTEND is often the clearer choice.

OPEN EXTEND: append new records

Use OPEN EXTEND when the program must keep existing records and add new records at the end. Audit logs, transaction history files, and daily append files often use this mode.

OPEN EXTEND AUDIT-FILE
IF WS-AUDIT-STATUS = "00"
   MOVE WS-AUDIT-TEXT TO AUDIT-REC
   WRITE AUDIT-REC
ELSE
   DISPLAY "AUDIT OPEN FAILED: " WS-AUDIT-STATUS
END-IF

If the file may not exist yet, review whether the file should be defined as OPTIONAL. IBM documents different open results for available and unavailable files, so this choice should be deliberate rather than left to a copied file definition.

File status codes to check after OPEN

Every production COBOL program should check FILE STATUS after OPEN. The exact value depends on file organization and runtime behavior, but these statuses appear often in support work.

Status Typical meaning during OPEN First check
00 Open completed normally. Continue processing.
05 Optional file was not available, but open processing continued. Confirm whether SELECT OPTIONAL is intended.
35 Required file was not found or not available. Check the DD statement, catalog entry, and data set name.
39 File attributes do not match the COBOL description. Compare RECFM, LRECL, keys, and record layout.

JCL checks before changing the mode

The COBOL source is only half of the story. The DD statement must point to the right data set and allow the intended action. Before changing an open mode, check the production JCL and scheduler variables.

//CUSTIN   DD DSN=PROD.CUSTOMER.INPUT,DISP=SHR
//REPTDD   DD DSN=PROD.REPORT.DAILY,
//            DISP=(NEW,CATLG,DELETE),
//            SPACE=(CYL,(5,2)),
//            DCB=(RECFM=FB,LRECL=133)

For read-only files, DISP=SHR is common. For new output files, the job often uses DISP=(NEW,CATLG,DELETE). For update jobs, review enqueue rules, restart behavior, and whether another job can read the same data set while updates are running.

Common mistakes

Opening an input file as OUTPUT

This is the dangerous one. A copy-paste change can replace a file that should only be read. Review OPEN OUTPUT statements carefully during code review.

Skipping FILE STATUS after OPEN

If the program does not test the status, the next READ or WRITE may fail far away from the real problem. Log the DD name and status so production support can act quickly.

Using EXTEND when the file is not optional

OPEN EXTEND can fail when a required file is missing. If the first run should create the file, define and test that behavior before the job reaches production.

Practical rule for choosing the mode

  • Use INPUT when the program only reads.
  • Use OUTPUT when the program creates a new result or intentionally replaces old contents.
  • Use I-O when the program reads existing records and updates or deletes them.
  • Use EXTEND when the program keeps existing records and appends new ones.
  • Always check FILE STATUS immediately after the OPEN.

Related Mainframe Forum guides

For the next file-handling topics, read COBOL File Operation, COBOL OPEN Statement, COBOL READ Statement, COBOL File Status, COBOL File Organization, and COBOL FD Entries.

External references

IBM documents these details in the Enterprise COBOL OPEN statement, OPEN statement notes, and opening ESDS, KSDS, and RRDS files pages.

FAQ

Which COBOL open mode is used for reading?

Use OPEN INPUT when the program only needs to read records from an existing file.

Which COBOL open mode appends records?

Use OPEN EXTEND when the program needs to add records after the last existing record.

Can COBOL read and update the same file?

Yes, but the file must be opened with OPEN I-O, and the file organization and access mode must support the update operation.

Why is OPEN OUTPUT risky?

OPEN OUTPUT is risky because it can replace existing records. Use it only when the job is meant to create a fresh output file or clear old contents.

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.

COBOL Fixed vs Variable-Length Records: FB, VB, and FD Examples

A COBOL program does not read a file as a vague stream of bytes. The FD entry, record description, and data set attributes tell the runtime whether every row has the same size or whether each row can be different. That choice affects READ, WRITE, file status codes, and the JCL used to allocate the data set.

COBOL fixed and variable length records diagram comparing FB RECORD CONTAINS and VB RECORD VARYING
Match the FD to the file.

What is a fixed-length record in COBOL?

A fixed-length record has the same logical length for every record in the file. If a customer extract uses 80 bytes per row, record 1 is 80 bytes, record 2 is 80 bytes, and the last record is also 80 bytes. On z/OS, this is commonly paired with a fixed record format such as RECFM=FB.

FILE SECTION.
FD  CUSTOMER-FILE
    RECORD CONTAINS 80 CHARACTERS.
01  CUSTOMER-REC.
    05  CUSTOMER-ID        PIC X(10).
    05  CUSTOMER-NAME      PIC X(30).
    05  CUSTOMER-STATUS    PIC X(01).
    05  FILLER             PIC X(39).

This layout is easy to test because every READ returns the same shape. It is also friendly to sort, copy, and compare jobs because positions stay stable. If account status is byte 41 today, it is byte 41 on every record.

What is a variable-length record in COBOL?

A variable-length record can hold rows with different logical lengths. One record might carry only a short header. Another record might carry a detail area with repeated values. COBOL describes this with a variable record clause or with record descriptions that make the compiler infer variable format.

FILE SECTION.
FD  ORDER-FILE
    RECORD IS VARYING FROM 20 TO 400 CHARACTERS
    DEPENDING ON WS-ORDER-LENGTH.
01  ORDER-REC.
    05  ORDER-ID           PIC X(10).
    05  ITEM-COUNT         PIC 9(03).
    05  ITEM-LINE          OCCURS 1 TO 20 TIMES
                           DEPENDING ON ITEM-COUNT.
        10 ITEM-CODE       PIC X(08).
        10 ITEM-QTY        PIC 9(03).

The DEPENDING ON value must match the real data being written or read. If the program says a record is shorter than it really is, useful bytes may be missed. If it says the record is longer than it really is, the next process may see padded or leftover data.

Fixed vs variable records at a glance

Area Fixed-length record Variable-length record
Typical z/OS format RECFM=FB RECFM=VB
COBOL FD clue RECORD CONTAINS 80 CHARACTERS RECORD IS VARYING FROM 20 TO 400
Best fit Stable rows, fixed reports, code tables, positional feeds Optional fields, repeated groups, message-style records
Main support risk Wrong LRECL or shifted field positions Wrong length value, ODO mismatch, reader expects fixed rows

How COBOL decides the record format

IBM Enterprise COBOL can use the RECORDING MODE clause for QSAM files. RECORDING MODE F is fixed. RECORDING MODE V is variable. If you omit it, the compiler can infer the mode from the RECORD clause and the level-01 record descriptions.

If all associated level-01 records are the same size and none contains OCCURS DEPENDING ON, the file is a natural fixed-record candidate. If record descriptions differ in size, or one contains OCCURS DEPENDING ON, the file usually belongs in the variable-record camp.

JCL and data set attributes still matter

The COBOL source and the JCL allocation must agree. A COBOL program compiled for an 80-byte fixed file should not be pointed at a variable blocked file and expected to behave like nothing changed.

//FIXIN    DD DSN=PROD.CUST.FIXED,
//            DISP=SHR,
//            DCB=(RECFM=FB,LRECL=80)
//VARIN    DD DSN=PROD.ORDER.VARIABLE,
//            DISP=SHR,
//            DCB=(RECFM=VB,LRECL=404)

For variable blocked records on z/OS, remember that the data set length includes control bytes used by the access method. Your COBOL record description describes the business data. The runtime and access method handle the record and block descriptor fields outside your 01 layout.

Common mistakes

Treating VB like FB

A reader that assumes fixed positions can fail when the input is variable. Check every later step, especially sort control cards, report programs, file transfers, and quick one-off copy jobs.

Using OCCURS DEPENDING ON without setting the count

The count field is not decoration. It controls how many table entries are part of the current record. Set it before WRITE, and validate it after READ if bad input can reach the job.

Changing the FD but not the JCL

A source change can look correct and still fail in production if the DD statement or cataloged data set attributes still describe the old record format.

Production checklist

  • Confirm the intended data set format: FB, VB, or another format.
  • Match the COBOL FD record clause to the largest and smallest valid business record.
  • Check OCCURS DEPENDING ON values before writing variable records.
  • Test the shortest record, the longest record, and a normal middle-size record.
  • Review downstream jobs that use SORT, COPY, FTP, or reporting tools.

Related Mainframe Forum guides

For surrounding file-handling topics, read COBOL READ Statement, COBOL OPEN Statement, COBOL File Status, COBOL File Operation, COBOL File Organization, and COBOL Block vs Unblock Records.

External references

IBM documents these rules in the Enterprise COBOL RECORDING MODE clause, defining variable-length records, and defining fixed-length records pages.

FAQ

What is the main difference between fixed and variable-length records?

A fixed-length file uses the same record size for every row. A variable-length file allows different rows to have different sizes, within the limits declared for the file.

When should I use fixed-length records?

Use fixed-length records when the layout is stable and every row can use the same length. They are simple to read, sort, compare, and support.

When should I use variable-length records?

Use variable-length records when rows naturally change size, such as records with optional trailing data or repeated groups controlled by OCCURS DEPENDING ON.

Does COBOL include RDW and BDW fields in my 01 record?

No. For normal QSAM variable records, descriptor fields are handled outside the COBOL record description. Your 01 layout describes the application data.

COBOL Sequential File Organization: READ, WRITE, and EOF

A daily billing job often reads yesterday's transaction file from top to bottom, totals the amounts, writes a report, and stops when it reaches end-of-file. That is the natural fit for COBOL sequential file organization: records are processed in the order they were written.

COBOL sequential file organization diagram showing records read in stored order until end of file
Read records in stored order.

What is a COBOL sequential file?

A sequential file stores records in a fixed order. IBM describes sequential organization as a predecessor-successor relationship: each record, except the first and last, has one record before it and one record after it. A program reads the records one after another.

Sequential organization works well when the job processes most or all records. Payroll extracts, report input files, unload files, tape files, and batch interface files often use this style.

How sequential access works

With sequential access, the program cannot jump directly to record 200 without reading the earlier records first. That sounds limiting, but it is efficient for full-file processing because records are read in order and can be blocked.

OPEN INPUT EMPLOYEE-FILE

PERFORM UNTIL WS-END-OF-FILE = 'Y'
   READ EMPLOYEE-FILE
      AT END
         MOVE 'Y' TO WS-END-OF-FILE
      NOT AT END
         PERFORM PROCESS-EMPLOYEE
   END-READ
END-PERFORM

CLOSE EMPLOYEE-FILE

FILE-CONTROL example

The FILE-CONTROL paragraph connects the COBOL file name to an external data set or ddname. If the ORGANIZATION clause is omitted, IBM Enterprise COBOL assumes ORGANIZATION IS SEQUENTIAL, but coding it explicitly is easier for learners and code reviewers.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
    SELECT EMPLOYEE-FILE
        ASSIGN TO EMPIN
        ORGANIZATION IS SEQUENTIAL
        ACCESS MODE IS SEQUENTIAL
        FILE STATUS IS WS-EMP-STATUS.

FD and record layout example

The FD entry describes the file in the FILE SECTION. The record description that follows tells COBOL how to move bytes from the file buffer into fields.

DATA DIVISION.
FILE SECTION.
FD  EMPLOYEE-FILE
    RECORD CONTAINS 80 CHARACTERS.
01  EMPLOYEE-RECORD.
    05 EMPLOYEE-ID        PIC X(06).
    05 EMPLOYEE-NAME      PIC X(30).
    05 EMPLOYEE-DEPT      PIC X(04).
    05 EMPLOYEE-SALARY    PIC 9(07)V99.
    05 FILLER             PIC X(31).

Sequential file operations

Operation Typical statement Common use
Read existing records OPEN INPUT, READ Batch input, report input, unload processing.
Create a new file OPEN OUTPUT, WRITE New extract or report file.
Add records at the end OPEN EXTEND, WRITE Append records to an existing sequential file.
Update current record REWRITE Allowed only in the proper open/access context and without changing fixed record length.

QSAM, VSAM ESDS, and line sequential

On z/OS, COBOL sequential files are commonly handled through QSAM for physical sequential data sets or through VSAM for ESDS files. IBM also documents line-sequential files for z/OS UNIX files, where records contain character data and end with a newline-style record delimiter.

QSAM sequential file

Use QSAM when the job reads or writes a physical sequential data set, including many tape and batch interface files. It is the normal choice for simple full-file processing.

VSAM ESDS

A VSAM entry-sequenced data set is also sequential by nature. Records are stored in entry order. Use ESDS when the site design needs VSAM services but the program still processes records sequentially.

Line sequential

Line-sequential files are character-oriented files. IBM notes that they are used for z/OS UNIX file-system data and each record ends with a record delimiter. They are not the same thing as a standard MVS QSAM data set.

When to sort a sequential file

A sequential file is often useful only when it is in the order the program expects. A billing job may need account number order. A report may need department order. If the incoming file arrives in a different order, sort it before the COBOL step or use a COBOL SORT statement when that fits the site standard.

//SORTIN   DD DSN=PROD.TRANS.UNSORTED,DISP=SHR
//SORTOUT  DD DSN=PROD.TRANS.BYACCT,DISP=(NEW,CATLG,DELETE),
//            SPACE=(CYL,(20,5)),UNIT=SYSDA
//SYSIN    DD *
  SORT FIELDS=(1,10,CH,A)
/*

Performance notes

Sequential files are fast when the program reads a large percentage of the file. IBM guidance says sequential access is usually faster than random or dynamic access when a large percentage of records is referenced or updated. The weak pattern is a program that repeatedly scans the same file looking for one record.

  • Use blocking for batch files instead of reading tiny physical blocks.
  • Process the file in the same order as the business key when possible.
  • Avoid reading the same file from the beginning inside another loop.
  • Use a sort, indexed file, database table, or lookup table when direct retrieval is needed.

Sequential vs indexed vs relative

Need Better file organization Reason
Read all records in order Sequential Simple and efficient for full-file batch work.
Find records by customer number Indexed Key access avoids scanning the whole file.
Access records by relative number Relative Record number controls placement and lookup.
Read text files in z/OS UNIX Line sequential Records are character data with delimiters.

Common mistakes

Using sequential files for repeated single-record lookup

If the program reads 500,000 records to find one account, and does that thousands of times, the file organization is probably wrong for the access pattern. Consider indexed access, DB2, or a preloaded table.

Missing file status checks

Always define a file status field and check it in error paths. End-of-file is expected. Status values such as open failure, write failure, or record-length issues need a message and a clear return code.

Confusing sequential and line sequential

A line-sequential file is not just a QSAM file with a different name. It is character-oriented and delimiter-based, so trailing blanks and record lengths can behave differently.

Related COBOL file topics

For nearby file-handling topics, read COBOL File Operation, COBOL File I/O Modes, COBOL File Status, COBOL Fixed and Variable Records, COBOL Indexed Sequential File, and COBOL Relative Organization.

External references

Technical notes in this refresh were checked against IBM COBOL file organization documentation, IBM guidance for choosing file organization and access mode, and IBM FILE-CONTROL paragraph documentation.

FAQ

What is sequential file organization in COBOL?

It is a file organization where records are processed in the order they were placed in the file. The program reads records one after another until end-of-file.

Can a COBOL sequential file be read randomly?

No. A sequential file is read sequentially. Use indexed or relative organization when the program needs random or dynamic access.

When is a sequential file a good choice?

Use it for full-file batch processing, reports, unloads, tape files, and interface files where most records are read or written in order.

Is line sequential the same as sequential?

No. Line sequential is character-oriented and delimiter-based, often used for z/OS UNIX files. Standard sequential files on z/OS are commonly QSAM or VSAM sequential files.

COBOL Indexed File Organization: RECORD KEY and READ Examples

A customer inquiry screen usually cannot read a file from the first record until it finds account 000417. The program needs to place a key value in a field, issue a keyed read, and get the matching record. That is the job of COBOL indexed file organization.

COBOL indexed file organization diagram showing a program using RECORD KEY to read a VSAM KSDS record
Key lookup plus ordered reads.

What is a COBOL indexed file?

An indexed file stores records with one or more key fields inside the record. The prime key identifies the record, and the index gives COBOL a logical path to the data. On z/OS, this is commonly coded for a VSAM key-sequenced data set, or KSDS.

IBM documents indexed organization as a file type where each record has embedded keys and each key is associated with an index. The prime key must be unique, and COBOL uses the RECORD KEY clause in FILE-CONTROL to name that field.

When indexed organization fits

Use an indexed file when the program needs direct lookup by key and also needs to process records in key order. A batch job can read the file from the lowest customer number to the highest, while an online or inquiry-style program can read one customer directly by account number.

Need Indexed file fit
Read one employee by employee number Good fit because the prime key points to one record.
Print all accounts in account number order Good fit because sequential access follows key order.
Read by department as a second path Possible with an alternate record key when the file design supports it.
Read every record once with no key lookup A plain sequential file may be simpler.

FILE-CONTROL for an indexed file

The indexed file definition belongs in the FILE-CONTROL paragraph. The important parts are ORGANIZATION IS INDEXED, an access mode, a RECORD KEY, and a file status field.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
    SELECT CUSTOMER-FILE
        ASSIGN TO CUSTKSDS
        ORGANIZATION IS INDEXED
        ACCESS MODE IS DYNAMIC
        RECORD KEY IS CUSTOMER-ID
        ALTERNATE RECORD KEY IS CUSTOMER-ZIP
            WITH DUPLICATES
        FILE STATUS IS WS-CUST-STATUS.

ACCESS MODE IS DYNAMIC lets the program switch between keyed lookup and ordered reading. Use RANDOM when the program only reads by key. Use SEQUENTIAL when the program only walks the file in key order.

Record layout example

The key field named in RECORD KEY must be part of the record description. In this example, CUSTOMER-ID is the prime key. CUSTOMER-ZIP is an alternate key that can return more than one record when duplicates are allowed.

DATA DIVISION.
FILE SECTION.
FD  CUSTOMER-FILE.
01  CUSTOMER-RECORD.
    05 CUSTOMER-ID        PIC X(10).
    05 CUSTOMER-NAME      PIC X(30).
    05 CUSTOMER-ZIP       PIC X(05).
    05 CUSTOMER-BALANCE   PIC S9(7)V99 COMP-3.
    05 FILLER             PIC X(40).

Random READ by prime key

For a direct lookup, move the wanted key value into the record key field before the READ. A status of 00 means the record was found. A status of 23 commonly means the key was not found for indexed and relative files.

MOVE '0000000417' TO CUSTOMER-ID

READ CUSTOMER-FILE
    INVALID KEY
        DISPLAY 'CUSTOMER NOT FOUND: ' CUSTOMER-ID
    NOT INVALID KEY
        PERFORM DISPLAY-CUSTOMER
END-READ

START and READ NEXT

START positions the indexed file at a key. READ NEXT then reads forward from that point. This pattern is useful for range processing, such as all customers from account 000400 upward or all keys in a department sequence.

MOVE '0000000400' TO CUSTOMER-ID

START CUSTOMER-FILE
    KEY IS GREATER THAN OR EQUAL TO CUSTOMER-ID
    INVALID KEY
        MOVE 'Y' TO WS-END-OF-FILE
END-START

PERFORM UNTIL WS-END-OF-FILE = 'Y'
    READ CUSTOMER-FILE NEXT RECORD
        AT END
            MOVE 'Y' TO WS-END-OF-FILE
        NOT AT END
            PERFORM PROCESS-CUSTOMER
    END-READ
END-PERFORM

Alternate record keys

An alternate key gives the program a second path into the same indexed file. For example, the prime key may be employee number, while an alternate key may be department. IBM notes that alternate keys can be used to access records in a sequence other than the prime-key sequence.

Alternate keys can be unique or can allow duplicates. If duplicates are allowed, the program must be written to handle more than one matching record. Do not add alternate indexes casually; each insert, delete, or key-changing update has more index work to maintain.

File status checks

Indexed files need clear file status handling because a failed keyed read is not always a program failure. A missing customer record may be a normal business case, while an open error or duplicate prime key on write should usually stop the job or return a controlled error.

Status Meaning in common indexed-file logic
00 Successful operation.
02 Successful operation with a duplicate alternate key condition.
10 End-of-file during sequential reading.
22 Duplicate key on write or rewrite.
23 Record not found for a keyed operation.

Indexed vs sequential vs relative files

A sequential file is best when the program reads records in stored order and does not need direct lookup. A relative file is best when the record number itself is the access path. An indexed file is the normal COBOL choice when the business key matters.

Read COBOL Sequential File Organization and COBOL Relative Organization for the nearby file organization choices.

Common mistakes

Changing the prime key during REWRITE

The prime key identifies the record. Do not design update logic that changes the prime key inside a rewrite path. Delete and recreate only when the application design and recovery rules allow it.

Using random access for range work

Random access is right for one key. For a range, use START and READ NEXT. That keeps the program in key order and avoids repeated single-record calls when a sequential pass would be cleaner.

Ignoring alternate-key duplicates

If the alternate key allows duplicates, one key value can represent several records. Code the loop and stop condition carefully, especially for department, location, state, or date fields.

Related mainframe topics

For more COBOL file handling, read COBOL File Operation, COBOL File I/O Modes, COBOL File Status, COBOL Fixed and Variable Records, VSAM IDCAMS Program, and when to use VSAM KSDS, ESDS, RRDS, and LDS.

External references

Technical notes in this refresh were checked against IBM COBOL file organization documentation, IBM access mode rules, IBM VSAM indexed file coding, and IBM alternate key guidance.

FAQ

What is indexed file organization in COBOL?

It is a file organization where records contain key fields and an index provides the path to retrieve records by key or read them in key order.

What is RECORD KEY in COBOL?

RECORD KEY names the prime key field for an indexed file. The program uses that key field for direct access and ordered processing.

Can indexed files be read sequentially?

Yes. Indexed files can use sequential, random, or dynamic access. Sequential access reads records in key order.

When should I use START in COBOL?

Use START when the program needs to position an indexed file at a key before reading the next records in sequence.

New In-feed ads