I/O Operations in COBOL
Master input and output in COBOL - console DISPLAY/ACCEPT, formatted output with PIC clauses, and sequential file reading and writing with GnuCOBOL
Input and output are where COBOL shows its true colors. The language was born in 1959 to process business records - reading files, transforming data, and writing reports - so its I/O model is one of the most mature and precisely controlled of any language. Where modern languages treat file handling as an afterthought, COBOL bakes it into the program structure through the ENVIRONMENT and DATA divisions.
COBOL separates I/O into two worlds. Console I/O uses the simple DISPLAY and ACCEPT verbs to talk to the terminal. File I/O is far more structured: you declare a file in the FILE-CONTROL paragraph, describe its record layout with an FD (File Description) entry, and then OPEN, READ/WRITE, and CLOSE it. Every byte of every record has a defined position and picture.
This precision is why COBOL still runs banking and government systems: a PIC 9(6) field is always six digits, and a record layout written in 1975 reads exactly the same way today. In this tutorial you’ll learn formatted console output, interactive input, and how to write and read sequential files - the everyday tools of COBOL data processing.
Formatted Console Output
You already met DISPLAY in Hello World. Its real power emerges with numeric-edited pictures, which turn raw numbers into human-readable output. DISPLAY ... WITH NO ADVANCING suppresses the newline so you can build a line piece by piece.
Create a file named display.cob:
| |
A few things are happening here:
WS-COUNTis stored as042- numeric fields carry leading zeros, andDISPLAYshows them literally.WS-CURRENCYuses an edited picture. TheZcharacters suppress leading zeros (turning them into spaces), while,and.are inserted literally. Moving1234.56intoZ,ZZ9.99produces1,234.56.FUNCTION TRIMstrips the trailing spaces that pad the fixed-widthPIC X(15)field.WITH NO ADVANCINGkeeps the cursor on the same line so threeDISPLAYstatements build one line of output.
Interactive Input with ACCEPT
The ACCEPT verb reads a line from standard input into a data item. COBOL moves the typed characters into the receiving field according to its picture, so text goes into PIC X fields and digits into PIC 9 fields. ACCEPT ... FROM DATE (and FROM TIME) pulls values from the system instead of the keyboard.
Create a file named accept.cob:
| |
Because ACCEPT reads interactively, output depends on what the user types. A sample session (with the user entering Grace Hopper and Philadelphia) looks like this:
Enter your name: Grace Hopper
Enter your city: Philadelphia
Welcome, Grace Hopper!
You are visiting from Philadelphia.
Today's date (YYMMDD): 260702
The ACCEPT WS-TODAY FROM DATE line reads the current date as YYMMDD (here, July 2, 2026 → 260702) - a handy way to timestamp reports without any external library.
Writing a Sequential File
File I/O is where COBOL’s structure pays off. To use a file you must declare it in three places: FILE-CONTROL (name and organization), an FD entry (the record layout), and the PROCEDURE DIVISION (the OPEN/WRITE/CLOSE logic). We use ORGANIZATION IS LINE SEQUENTIAL, which writes plain text lines - the most portable file format.
Create a file named filewrit.cob:
| |
Key ideas:
SELECT ... ASSIGN TO "sales.dat"maps the internal file nameREPORT-FILEto a real file on disk.- The
FDentry defines a fixed 22-byte record: 12 characters of product name, 4 digits of units, 6 digits of revenue. Every record has this exact layout. OPEN OUTPUTcreates (or truncates) the file. You mustOPENbefore anyWRITEandCLOSEwhen done.- Each
WRITE SALES-RECORDflushes the current contents of the record area to disk as one line. Because the fields are fixed-width,Keyboardis padded to 12 characters and numbers keep their leading zeros.
Reading a Sequential File
Reading walks through the file record by record. The READ ... AT END construct handles the end-of-file condition, and a PERFORM UNTIL loop keeps reading until there are no more records. This example also adds a FILE STATUS field to catch I/O errors - the standard COBOL way to handle a missing or unreadable file.
Create a file named fileread.cob:
| |
How the read loop works:
FILE STATUS IS WS-FILE-STATUSgives you a two-character code after each I/O operation."00"means success; anything else signals a problem (for example,"35"for a file that doesn’t exist). Checking it afterOPENis defensive programming COBOL shops rely on.READ REPORT-FILEloads the next record intoSALES-RECORD. TheAT ENDbranch fires when there are no more records;NOT AT ENDruns for each successful read.- The loop uses the
WS-EOFflag as its exit condition - a classic COBOL idiom since the language has nobreakstatement. - Reading fills the same fixed-width fields defined in the
FD, soSR-UNITSandSR-REVENUEcome back as the exact digit strings that were written.
Running with Docker
The examples run in the official GnuCOBOL image. The -x flag builds an executable and -free enables free-format source. The file examples must run in order (write creates sales.dat, then read consumes it).
| |
Expected Output
The formatted output example (display.cob) prints:
Item count: 042
Price: $1,234.56
Language: COBOL
Progress: 50% complete
The write-then-read sequence (filewrit.cob followed by fileread.cob) prints:
Wrote 3 records to sales.dat
Product: Keyboard | Units: 0150 | Revenue: 004500
Product: Monitor | Units: 0075 | Revenue: 022500
Product: Mouse | Units: 0300 | Revenue: 003600
Total records read: 03
Key Concepts
- Console vs. file I/O are separate worlds -
DISPLAY/ACCEPTfor the terminal, and a fullFILE-CONTROL+FD+OPEN/READ/WRITE/CLOSEpipeline for files. - Edited pictures format numbers for humans -
Zsuppresses leading zeros while,.$are inserted literally, so raw numeric fields become readable reports without string juggling. - Every file has a fixed record layout - the
FDentry defines exact byte positions withPICclauses, which is why a COBOL data file stays readable for decades. OPENbefore use,CLOSEwhen done - files must be opened in the right mode (OUTPUT,INPUT,EXTEND, orI-O) before any read or write.READ ... AT ENDdrives the read loop - combined with aPERFORM UNTILflag, it’s the canonical way to process a sequential file since COBOL has nobreak.FILE STATUSis your error handling - a two-character code after every operation ("00"= success) lets you catch missing files and I/O failures gracefully.ORGANIZATION IS LINE SEQUENTIALproduces portable plain-text files, ideal for interoperating with modern tools; classic mainframe code often uses record-orientedSEQUENTIALor indexed files instead.
Running Today
All examples can be run using Docker:
docker pull esolang/cobol:latest
Comments
Loading comments...
Leave a Comment