I am trying to find out a way to check whether a file is already opened in COBOL, so that I can open it if it is closed or close it if it is opened.
Thnx.
Check the FILE STATUS
and act accordingly.
Try the following:
Add a FILE-STATUS
under the FILE-CONTROL
, for example:
FILE-CONTROL.
SELECT MYFILE ASSIGN MYDD
ORGANIZATION SEQUENTIAL
ACCESS SEQUENTIAL
FILE STATUS MYFILE-STATUS.
Declare a FILE STATUS
variable in WORKING-STORAGE
as a PIC X(2)
value, for example:
01 MYFILE-STATUS PIC X(2).
88 MYFILE-ALREADY-OPEN VALUE '41'.
Then in the PROCEDURE DIVISION
issue an OPEN
for your
file. Immediately following that, test the value of FILE STATUS
as in:
OPEN MYFILE....
IF MYFILE-ALRADY-OPEN
CLOSE MYFILE...
END-IF
IF MYFILE-STATUS <> '00'
perform some sort of general error routine
END-IF
Values of FILE STATUS
where the first character is not a '9', are
COBOL standard values so testing for '41' to detect an already open file
should work on all COBOL implementations. Beware when the first character is a '9',
these are vendor specific file status codes. Check out the following link for
a good introduction to using COBOL FILE STATUS
: http://www.simotime.com/vsmfsk01.htm