Showing posts with label COBOL READ. Show all posts
Showing posts with label COBOL READ. Show all posts

Tuesday, 12 August 2014

COBOL READ Statement: Sequential, Random & Dynamic Examples

READ CUSTOMER-FILE AT END ... END-READ retrieves the next logical record or runs the end-of-file branch. The file must already be open for INPUT or I-O, and the program must not use the record area after an unsuccessful read.

COBOL READ statement flow from OPEN through READ and FILE STATUS to record processing
A READ retrieves one logical record, sets FILE STATUS, and selects the success or error path.

What the COBOL READ statement requires

The file name in a READ names an FD, not a record layout. Its SELECT entry defines the organization and access mode, while the FD defines the record area. Before the first read, issue OPEN INPUT when the program only reads the file or OPEN I-O when it can also update records.

SELECT CUSTOMER-FILE ASSIGN TO CUSTIN ORGANIZATION IS SEQUENTIAL ACCESS MODE IS SEQUENTIAL FILE STATUS IS WS-FILE-STATUS. FD CUSTOMER-FILE. 01 CUSTOMER-RECORD. 05 CUST-ID PIC 9(8). 05 CUST-NAME PIC X(30).

The COBOL file operations guide covers the wider OPEN, READ, WRITE, REWRITE, and CLOSE lifecycle. This page concentrates on READ syntax and the branches a program must handle.

READ syntax by access pattern

Access patternTypical formCondition to handle
Sequential fileREAD file [INTO target] AT END ... END-READAT END or status 10
Indexed file, random accessREAD file [INTO target] KEY IS key-name INVALID KEY ... END-READINVALID KEY, commonly status 23 when a record is not found
Indexed file, dynamic accessREAD file NEXT RECORD [INTO target] AT END ... END-READAT END after positioning for sequential retrieval
Relative file, random accessSet the relative key, then READ file ... INVALID KEY ... END-READINVALID KEY; the READ does not use a KEY IS phrase

NEXT is optional for a sequential file because sequential retrieval is already implied. It is required when a file opened with dynamic access is to retrieve the next record rather than perform a random read.

Sequential READ with an EOF loop

A safe loop initializes its own EOF switch, lets AT END set that switch, and processes the record only under NOT AT END.

MOVE 'N' TO WS-EOF OPEN INPUT CUSTOMER-FILE PERFORM UNTIL WS-EOF = 'Y' READ CUSTOMER-FILE AT END MOVE 'Y' TO WS-EOF NOT AT END PERFORM PROCESS-CUSTOMER END-READ END-PERFORM CLOSE CUSTOMER-FILE

When no next record exists, COBOL sets the file status before it runs the AT END statements. IBM also documents the record area as undefined after an unsuccessful READ. Keeping record processing inside NOT AT END prevents stale or unpredictable data from entering the next calculation.

QSAM warning: do not refer to the file's record area after a failed read. Depending on the access method and runtime state, doing so can cause a protection exception rather than merely return the previous record.

For a longer example that reads and writes sequential records, see COBOL sequential file organization.

How READ INTO works

The INTO phrase adds an implicit move after a successful read. COBOL first makes the current record available in the file's record area and then moves it to the receiving item. If the read fails, that move does not occur.

READ CUSTOMER-FILE INTO WS-CUSTOMER AT END MOVE 'Y' TO WS-EOF NOT AT END PERFORM VALIDATE-CUSTOMER END-READ
Choose one ownership rule: process the FD record area directly, or use READ INTO and process the working-storage copy. Mixing the two without a reason makes record changes harder to follow.

Random READ for an indexed file

Random access to an indexed file compares the key of reference with the indexed key. Move the requested value to that key before issuing the read. If no matching record exists, COBOL runs the INVALID KEY branch and sets FILE STATUS.

MOVE WS-REQUESTED-ID TO CUST-ID READ CUSTOMER-FILE INTO WS-CUSTOMER KEY IS CUST-ID INVALID KEY DISPLAY 'CUSTOMER NOT FOUND, STATUS=' WS-FILE-STATUS NOT INVALID KEY PERFORM SHOW-CUSTOMER END-READ

An indexed file can define alternate record keys, so the selected key must match a key named for that file. The COBOL indexed-file guide covers primary keys, alternate keys, and duplicate-key rules.

Dynamic access: START and READ NEXT

Dynamic access allows random and sequential operations in the same run. A common pattern uses START to establish a position and then READ NEXT RECORD to walk forward in key sequence.

MOVE WS-LOW-CUST-ID TO CUST-ID START CUSTOMER-FILE KEY IS NOT LESS THAN CUST-ID INVALID KEY MOVE 'Y' TO WS-EOF END-START PERFORM UNTIL WS-EOF = 'Y' READ CUSTOMER-FILE NEXT RECORD AT END MOVE 'Y' TO WS-EOF NOT AT END PERFORM PROCESS-CUSTOMER END-READ END-PERFORM

The sequence after START follows the key of reference. If an alternate key established the position, subsequent sequential reads use that key order until another operation changes the reference. See the COBOL START statement for its comparison conditions and positioning rules.

Random READ for a relative file

A relative file uses the data item named by the RELATIVE KEY clause. Set that relative record number before a random read. Unlike an indexed random read, the relative-file READ does not specify a KEY IS phrase.

MOVE 125 TO WS-RELATIVE-KEY READ ORDER-FILE INTO WS-ORDER INVALID KEY DISPLAY 'RELATIVE RECORD NOT FOUND, STATUS=' WS-ORDER-STATUS NOT INVALID KEY PERFORM PROCESS-ORDER END-READ

The COBOL relative organization guide explains relative keys and record-number access in more detail.

FILE STATUS values to check after READ

A FILE STATUS data item is updated after every input/output operation. Declaratives and runtime settings can affect handling, but these common two-character values are a useful starting point.

StatusMeaning in a READ pathTypical response
00Successful completionProcess the record.
04Successful read with a record-length condition under applicable rulesCheck the FD, LRECL, record format, and compiler/runtime setting.
10No next logical record; end of fileEnd the sequential loop.
23Record not found or no record at the requested keyHandle the missing indexed or relative record.
47READ attempted when the file is not open for INPUT or I-OCorrect the OPEN mode and control flow.

Use the COBOL file status code reference when the status is not one of these common READ outcomes.

Which OPEN modes permit READ?

OPEN modeCan READ?Purpose
INPUTYesRead existing records without updating them.
I-OYesRead existing records and permit supported update operations.
OUTPUTNoCreate or replace output content.
EXTENDNoAdd records at the end of a supported sequential file.

Common READ mistakes

  • Processing after AT END: the record area is undefined after an unsuccessful read.
  • Omitting NEXT under dynamic access: a sequential retrieval from a dynamically accessed file needs NEXT RECORD.
  • Using KEY IS for a relative file: set the declared relative-key item instead.
  • Ignoring FILE STATUS: INVALID KEY and AT END handle branches, while the status supplies the diagnostic value.
  • Reading after OPEN OUTPUT: READ is allowed only after OPEN INPUT or OPEN I-O.
  • Assuming READ INTO bypasses the FD area: a successful read still makes the current record available in the file's record area before the implicit move.

Official IBM references

Frequently asked questions

What does the COBOL READ statement do?

READ retrieves one logical record from an open file. Sequential access gets the next record; random access gets the record identified by a key or relative record number.

What is the difference between READ and READ NEXT?

READ gets the next record automatically in sequential access mode. In dynamic access mode, READ with NEXT RECORD requests sequential retrieval from the current file position.

When should a COBOL program use AT END?

Use AT END for a sequential read when no next logical record exists. Do not process the record area after that unsuccessful read.

What does READ INTO do in COBOL?

READ INTO retrieves a record and then performs an implicit MOVE to the receiving data item. The move occurs only when the READ succeeds.

Working rule: after every READ, follow the success, AT END, or INVALID KEY path before touching the returned record.

Monday, 28 July 2014

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.

New In-feed ads