Close *ALL the files on-exit

I have previously mentioned the ON-EXIT operation code, and now it’s the turn of something I should have known about years ago.

Back in the old days, handling files was simple. All of the files you declared would be opened when the program starts and closed again when the program ends.

Now, however, the RPG Cycle is no longer used and all code is (or should be) broken out into discrete procedures. This means that we should also be manually opening and closing files as and when needed. The impact of this is that we need to ensure that any open files are closed when we exit a procedure.

The ON-EXIT opcode helps here, but it’s still a bit of a grind if you have to manually check and close every file that may still be open. It turns out, however, that you don’t need to as the CLOSE operation allows you to close all of the globally defined files at once.

Here’s an example. Run it in debug and watch those files magically close themselves when the program ends.

        ctl-opt dftactgrp(*no) actgrp(*new) main(Main);

        dcl-f LSM101P rename(LSM101P: LSM101R) usropn;
        dcl-f LSM102P rename(LSM102P: LSM102R) usropn;

        dcl-proc Main;

            dcl-pi *n end-pi;

            if not %open(LSM101P);
                open LSM101P;
            endif;

            if not %open(LSM102P);
                open LSM102P;
            endif;

            // Do some processing here
            read LSM101P;
            dsply DESC101;

            return;

        on-exit;
            close *all;

        end-proc;

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.