Community Help: Cobol File Read Example - Example of opening and reading file with Cobol
Share your own experience
View front page
This cobol example will show the basics for reading a file. It shows how to open the file, define the file, and read the file. It also shows the cobol variables and how they are defined, but of course some things are left out like how you want to loop through to read all the input data, etc., and of course you will want to close the file when done. This example will use cobol to open and read a variable length file that has 4000 bytes per row max. It also shows how to check the open and read to make sure it was successfull.
In your I/O section:
SELECT FILE-IN ASSIGN TO FILE-NAME-IN
FILE STATUS IS WS-STATUS-IN.
In your data division:
RECORDING MODE IS V.
01 SAMPLE-INPUT-PROF PIC X(4000).
In working storage, define:
05 WS-STATUS-IN PIC 9(02) VALUE ZERO.
In your cobol code:
OPEN INPUT SAMPLE-FILE
IF WS-STATUS-IN = 0
(You will loop through the reads)
READ FILE-IN INTO WS-I-REC
(Do something like close the file when done)
(Do something with various conditions)
(Do something if you had an open error)