BudiBadu Logo
Samplebadu

COBOL by Example: Sequential Files

COBOL 2002

Processing sequential files with OPEN INPUT/OUTPUT modes, reading records with READ AT END for end-of-file detection, mapping files in ENVIRONMENT DIVISION with SELECT ASSIGN, defining record layouts in FILE SECTION with FD, and using LINE SEQUENTIAL organization for text files.

Code

       IDENTIFICATION DIVISION.
       PROGRAM-ID. SEQ-FILES.
       
       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
           SELECT STUDENT-FILE ASSIGN TO "students.dat"
           ORGANIZATION IS LINE SEQUENTIAL.
           
       DATA DIVISION.
       FILE SECTION.
       FD  STUDENT-FILE.
       01  STUDENT-REC.
           05 ID-NUM   PIC 99.
           05 NAME     PIC X(10).
           
       WORKING-STORAGE SECTION.
       01  WS-EOF      PIC A VALUE 'N'.
       
       PROCEDURE DIVISION.
           OPEN INPUT STUDENT-FILE.
           PERFORM UNTIL WS-EOF = 'Y'
               READ STUDENT-FILE
                   AT END MOVE 'Y' TO WS-EOF
                   NOT AT END DISPLAY ID-NUM " " NAME
               END-READ
           END-PERFORM.
           CLOSE STUDENT-FILE.
           STOP RUN.

Explanation

File handling is a core strength of COBOL. Sequential files are the simplest type, where records are stored one after another. To use a file, you must map it in the ENVIRONMENT DIVISION (using SELECT) and define its layout in the FILE SECTION (using FD).

The standard pattern for processing a file is: OPEN, loop through READ until End-Of-File (EOF), and finally CLOSE. The AT END clause in the READ statement detects when there is no more data. It is common to use a flag (like WS-EOF) to control the loop.

There are different types of sequential files. LINE SEQUENTIAL is common on PC-based COBOL (like GnuCOBOL) for text files where each record ends with a newline. RECORD SEQUENTIAL (or just SEQUENTIAL) is often used on mainframes for fixed-length binary records without delimiters.

Code Breakdown

6
SELECT ... ASSIGN TO ... Maps the internal file name (STUDENT-FILE) to the physical file on disk ("students.dat").
7
ORGANIZATION IS LINE SEQUENTIAL. Specifies that this is a text file with newlines.
11
FD STUDENT-FILE. File Definition. Describes the structure of the records in the file.
20
OPEN INPUT. Opens the file for reading. You would use OPEN OUTPUT to write to a file (overwriting it).
21
PERFORM UNTIL WS-EOF = 'Y'. A standard read loop. It continues until the EOF flag is set.
23
AT END. This block executes when the read operation hits the end of the file, setting our EOF flag.
27
CLOSE STUDENT-FILE. Always close files to release system resources.