IBM Support

Simple Method to Check For Existence of Files in a Directory Using a CL Program

How To


Summary

This article has a working example of a CL program that checks for the existence of any files in a specific directory.

Objective

Most scripting languages have a simple mechanism to check for the existence of files in a directory.  CL programming on the IBM i platform does not.  While you could use API calls to accomplish this goal, APIs can be difficult to debug.  The following is a simpler method to achieve the result by using a shell script and data area incorporated into a CL program.

Steps

In this example, I show how to check for the existence of any files in the /home/mike directory.  The user running this script must be authorized to the path being checked, though not necessarily to the files in that path.  The root file system does not support adopted authority so this requirement really can't be worked around.  The program requires a shell script and a CL program. 
 
First, create the shell script, /mikswens/checkexists.qsh, by doing running the command

EDTF '/mikswens/checkexists.qsh'
 
Then, paste the following script into that file
 
if [ ! -z "$(ls -A /home/mikswens)" ]
  then
    system "CHGDTAARA DTAARA(MIKSWENS/FILEEXIST *ALL) VALUE(Y)"
  else
    system "CHGDTAARA DTAARA(MIKSWENS/FILEEXIST *ALL) VALUE(N)"
fi

Next, create a source physical file member for the CL source and open that member in an editor, paste the following source code into that file member, then save and compile the member.
 
PGM
   DCL VAR(&FILES) TYPE(*CHAR) LEN(1)
   CRTDTAARA DTAARA(MIKSWENS/FILEEXIST) TYPE(*CHAR) LEN(1) +
      TEXT('FOR USE WITH THE FILEEXIST PROGRAM') AUT(*CHANGE)
   MONMSG MSGID(CPF9999)
   QSH CMD('/mikswens/checkexist.qsh > nul')
   RTVDTAARA MIKSWENS/FILEEXIST RTNVAR(&FILES)
   IF COND(&FILES *EQ Y) THEN(DO)
      SNDPGMMSG  MSG('Files exist in /home/mike')
   ENDDO
   ELSE (DO)
      SNDPGMMSG MSG('No files exist in /home/mike')
   ENDDO
ENDPGM

This simple example just displays a message on your screen when it is called. You can modify the CL program DO/ENDDO blocks to do something more useful in a real world application.

Document Location

Worldwide

[{"Type":"MASTER","Line of Business":{"code":"LOB68","label":"Power HW"},"Business Unit":{"code":"BU070","label":"IBM Infrastructure"},"Product":{"code":"SWG60","label":"IBM i"},"ARM Category":[{"code":"a8m3p0000006x8GAAQ","label":"CL"},{"code":"a8m0z0000000CbFAAU","label":"Data Access-\u003EQShell"}],"ARM Case Number":"","Platform":[{"code":"PF012","label":"IBM i"}],"Version":"All Versions"}]

Document Information

Modified date:
17 June 2024

UID

ibm10795816