Reading Files in COBOL

Our first program will demonstrate how to read files in COBOL. Here’s the full source code:

IDENTIFICATION DIVISION.
PROGRAM-ID. FILE-READER.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
    SELECT INPUT-FILE ASSIGN TO "/tmp/dat"
    ORGANIZATION IS LINE SEQUENTIAL.

DATA DIVISION.
FILE SECTION.
FD INPUT-FILE.
01 FILE-RECORD.
   05 FILE-CONTENT PIC X(80).

WORKING-STORAGE SECTION.
01 WS-EOF PIC A(1).
01 WS-CONTENT PIC X(80).

PROCEDURE DIVISION.
MAIN-PROCEDURE.
    OPEN INPUT INPUT-FILE
    PERFORM READ-FILE UNTIL WS-EOF = 'Y'
    CLOSE INPUT-FILE
    STOP RUN.

READ-FILE.
    READ INPUT-FILE
        AT END
            MOVE 'Y' TO WS-EOF
        NOT AT END
            MOVE FILE-CONTENT TO WS-CONTENT
            DISPLAY WS-CONTENT.

This COBOL program demonstrates basic file reading operations. Let’s break down the key components:

  1. In the ENVIRONMENT DIVISION, we specify the input file and its organization.

  2. The DATA DIVISION defines the structure of the file record and working storage variables.

  3. The PROCEDURE DIVISION contains the main logic:

    • We open the input file.
    • We perform the READ-FILE procedure until we reach the end of the file.
    • We close the file when done.
  4. The READ-FILE procedure reads each record from the file and displays its content.

To run the program, compile the COBOL code and execute it:

$ cobc -x file-reader.cob
$ ./file-reader

This will display the contents of the “/tmp/dat” file.

Note that COBOL doesn’t have built-in functions for more advanced file operations like seeking to specific positions or buffered reading. These operations would require more complex programming or the use of lower-level file handling techniques specific to the COBOL implementation or operating system.

COBOL’s strength lies in its ability to handle structured data in files efficiently, especially for business-oriented tasks. For more complex file operations, you might need to use system-specific extensions or consider using a more modern language alongside COBOL in your workflow.