OPEN and CLOSE
Part of the Files and Reports section of Coddy's COBOL Programming journey. Lesson 2 of 22.
A file is opened before the program reads it. OPEN INPUT connects the file to its data set for reading, at the first record:
OPEN INPUT CUST-FILE.OPEN OUTPUT opens a file for writing instead. One OPEN can open several files, each after the word for its direction:
OPEN INPUT CUST-FILE RATE-FILE
OUTPUT LIST-FILE.CLOSE releases a file when the program is done with it. Close every file you open before STOP RUN:
CLOSE CUST-FILE RATE-FILE LIST-FILE.A READ on a file that is not open stops the program. GnuCOBOL reports file not open with status 47.
Challenge
EasyThe program reads two customers but never opens CUST-FILE, so it stops with an error. Open it for input before the first READ and close it after the last DISPLAY, so it prints Ann Lee and Bob Stone.
Try it yourself
IDENTIFICATION DIVISION.
PROGRAM-ID. OPENCL.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT CUST-FILE ASSIGN TO CUSTIN
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD CUST-FILE.
01 CUST-REC.
05 CUST-ID PIC X(4).
05 CUST-NAME PIC X(10).
05 CUST-CITY PIC X(6).
05 CUST-BAL PIC 9(5).
PROCEDURE DIVISION.
*> Open CUST-FILE here
READ CUST-FILE.
DISPLAY CUST-NAME.
READ CUST-FILE.
DISPLAY CUST-NAME.
*> Close CUST-FILE here
STOP RUN.