COBOL: Fix the file copy program (kind of)

I’m happy that I have learned some basic COBOL programming. I have no intention to become a professional COBOL developer, so I’ll keep it simple. In the last post I was trying to copy the contents from one file to another. It kind of worked, but not the way I inteded: the record delimiter didn’t really do its job and the program was not actually reading the file line by line. Here is a corrected version, but I couldn’t get it right with variable record length:

input.txt

line1
line2
line3

FILE.COB

       IDENTIFICATION DIVISION.
       PROGRAM-ID. READ-FILE.
       
       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
       SELECT INPUT-FILE 
           ASSIGN TO "input.txt"
           ORGANIZATION LINE SEQUENTIAL.
       SELECT OUTPUT-FILE ASSIGN TO "output.txt".
       
       DATA DIVISION.
       FILE SECTION.
       FD INPUT-FILE
           DATA RECORD IS INPUT-RECORD.    
       01 INPUT-RECORD.
          05 INPUT-TEXT   PIC X(5).
       FD OUTPUT-FILE
           DATA RECORD IS OUTPUT-RECORD.
       01 OUTPUT-RECORD.
          05 OUTPUT-TEXT PIC X(5).
       
       WORKING-STORAGE SECTION.
       01 WS-END-OF-FILE PIC 9(1) VALUE 0.
       
       PROCEDURE DIVISION.
       MAIN-LOGIC.
           OPEN INPUT INPUT-FILE
           OPEN OUTPUT OUTPUT-FILE
           READ INPUT-FILE INTO INPUT-RECORD
           PERFORM UNTIL WS-END-OF-FILE = 1          
               DISPLAY INPUT-TEXT
               MOVE INPUT-TEXT TO OUTPUT-TEXT
               WRITE OUTPUT-RECORD AFTER ADVANCING 1 LINE
               READ INPUT-FILE INTO INPUT-RECORD
               AT END SET WS-END-OF-FILE TO 1
           END-PERFORM
           CLOSE INPUT-FILE
           CLOSE OUTPUT-FILE
           STOP RUN.
       

Just compile it the standard way and it does the job!

The important bits are:

  • make sure the input file has fixed length records
  • special attention on the writing: only write the record after advancing one line, this ensures every record is written on a new line

That was great fun, next I would like to connect my COBOL application to a database. Let’s see how that will work out. 🙂

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.