Writing Files in COBOL

Here’s the translation of the Go code to COBOL, along with explanations in Markdown format suitable for Hugo:

Writing files in COBOL follows similar patterns to the ones we might use for reading.

To start, here’s how to write a string into a file:

IDENTIFICATION DIVISION.
PROGRAM-ID. WRITE-FILES.

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

DATA DIVISION.
FILE SECTION.
FD OUTFILE.
01 OUTFILE-RECORD PIC X(80).

WORKING-STORAGE SECTION.
01 WS-EOF         PIC A(1).
01 WS-STRING      PIC X(11) VALUE "hello COBOL".

PROCEDURE DIVISION.
MAIN-PROCEDURE.
    OPEN OUTPUT OUTFILE.
    MOVE WS-STRING TO OUTFILE-RECORD.
    WRITE OUTFILE-RECORD.
    CLOSE OUTFILE.
    STOP RUN.

For more granular writes, we can use a loop to write multiple records:

IDENTIFICATION DIVISION.
PROGRAM-ID. WRITE-MULTIPLE.

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

DATA DIVISION.
FILE SECTION.
FD OUTFILE.
01 OUTFILE-RECORD PIC X(80).

WORKING-STORAGE SECTION.
01 WS-EOF         PIC A(1).
01 WS-COUNTER     PIC 9(3) VALUE 1.

PROCEDURE DIVISION.
MAIN-PROCEDURE.
    OPEN OUTPUT OUTFILE.
    PERFORM WRITE-LOOP UNTIL WS-COUNTER > 5.
    CLOSE OUTFILE.
    STOP RUN.

WRITE-LOOP.
    MOVE SPACES TO OUTFILE-RECORD.
    STRING "Record #" WS-COUNTER INTO OUTFILE-RECORD.
    WRITE OUTFILE-RECORD.
    ADD 1 TO WS-COUNTER.

In COBOL, we don’t have the concept of buffered writers as in some other languages. File operations are typically buffered by the operating system.

To check the contents of the written files, you can use your system’s command line tools:

$ cat /tmp/dat1
hello COBOL
$ cat /tmp/dat2
Record #1
Record #2
Record #3
Record #4
Record #5

COBOL provides robust file handling capabilities, especially for structured data in business applications. The language is designed to work with record-based file systems, which is reflected in its file handling syntax.

Next, we’ll look at how to work with standard input and output streams in COBOL.