FILE OPEN Statement


  • OPEN statement establishes a connection between the logical file and its associated physical file.
  • It opens the file for subsequent processing (e.g., reading, writing, updating).
  • The program can't able to process a file without opening it.

Syntax -

OPEN opening-mode file-name.

Parameters -

  • opening-mode - Specifies the file opening mode. Mode is mandatory with OPEN statement.
  • file-name - Specifies 8-character logical file name defined inside the program. Multiple files can be opened with OPEN statement.

Opening Modes -

ModeDescription
INPUTFor reading operations only.
OUTPUT For writing operations only. If a file already exists, ts contents overwritten.
I-O For both reading and writing. Useful for updating files. The file should exist before to open in I-O mode.
EXTEND For appending records to an existing file. It applies for sequential access files only.

Allowed file operations based on OPEN modes -


For Sequential Files -

INPUT ModeOUTPUT ModeI-O ModeEXTEND Mode
READX X
WRITEX X
REWRITE X

For Indexed and Relative Files -

OperationINPUT ModeOUTPUT ModeI-O ModeEXTEND Mode
Sequential AccessREADXX
WRITEXX
REWRITEX
STARTXX
DELETEX
Random AccessREADXX
WRITEXX
REWRITEX
START
DELETEX
Dynamic AccessREADXX
WRITEXX
REWRITEX
STARTXX
DELETEX

Error Handling -


Let us assume the FILE STATUS clause is coded with a variable -

  • If the file opened successfully, the file status code is updated as ZERO (0).
  • If the file is not opened successfully, the file status code is updated with the error code.

The below table shows the possible file status codes when the OPEN statement failed -

File Opening modeFile Status if Unsuccessful
INPUT Open is unsuccessful. (file status 35)
I-O Open is unsuccessful. (file status 35)
OUTPUT Open causes the file to be created.
EXTEND Open is unsuccessful. (file status 35)
INPUT (optional file)
I-O (optional file)
EXTEND (optional file)
Open causes the file to be created. (file status 05)

Examples -


Scenario1 - Opening EMPFILE for reading.

 OPEN INPUT EMPFILE.

Scenario2 - Opening EMPFILE for writing.

 OPEN OUTPUT EMPFILE.

Scenario3 - Opening EMPFILE1, EMPFILE2 for reading.

 OPEN INPUT EMPFILE1
            EMPFILE2.