COBOL 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 -
| Mode | Description |
|---|---|
| INPUT | For 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 Mode | OUTPUT Mode | I-O Mode | EXTEND Mode | |
|---|---|---|---|---|
| READ | X | X | ||
| WRITE | X | X | ||
| REWRITE | X |
For Indexed and Relative Files -
| Operation | INPUT Mode | OUTPUT Mode | I-O Mode | EXTEND Mode | |
|---|---|---|---|---|---|
| Sequential Access | READ | X | X | ||
| WRITE | X | X | |||
| REWRITE | X | ||||
| START | X | X | |||
| DELETE | X | ||||
| Random Access | READ | X | X | ||
| WRITE | X | X | |||
| REWRITE | X | ||||
| START | |||||
| DELETE | X | ||||
| Dynamic Access | READ | X | X | ||
| WRITE | X | X | |||
| REWRITE | X | ||||
| START | X | X | |||
| DELETE | X |
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 mode | File 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.