Reading flat file in CL program |
Creating flat file
The “CRTPF” command is used to create a flat file (physical file without any source but with a record length) on IBM i.
CRTPF FILE(FLATFILE1) RCDLEN(80)
Create Physical File (CRTPF) Type choices, press Enter. File . . . . . . . . . . . . . . FILE FLATFILE1 Library . . . . . . . . . . . *CURLIB Source file . . . . . . . . . . SRCFILE QDDSSRC Library . . . . . . . . . . . *LIBL Source member . . . . . . . . . SRCMBR *FILE Record length, if no DDS . . . . RCDLEN 80 Generation severity level . . . GENLVL 20 Flagging severity level . . . . FLAG 0 File type . . . . . . . . . . . FILETYPE *DATA Member, if desired . . . . . . . MBR *FILE Text 'description' . . . . . . . TEXT *SRCMBRTXT
Here, In the file parameter provide the file name i.e, FLATFILE1, and provide a record number for example 80 in RCDLEN parameter.
CL program for Reading the flat file
PGM DCL VAR(&VAR1) TYPE(*CHAR) LEN(80) DCL VAR(&VAR2) TYPE(*CHAR) LEN(10) DCL VAR(&VAR3) TYPE(*CHAR) LEN(10) DCLF FILE(FLATFILE1) OPNID(FL1) READ: RCVF OPNID(FL1) MONMSG MSGID(CPF0864) EXEC(GOTO CMDLBL(END)) CHGVAR VAR(&VAR1) VALUE(&FL1_FLATFILE1) CHGVAR VAR(&VAR2) VALUE(%SST(&FL1_FLATFILE1 1 10)) CHGVAR VAR(&VAR3) VALUE(%SST(&FL1_FLATFILE1 11 10)) GOTO CMDLBL(READ) END: ENDPGM
Explanation of the above code:
DCL VAR(&VAR1) TYPE(*CHAR) LEN(80) DCL VAR(&VAR2) TYPE(*CHAR) LEN(10) DCL VAR(&VAR3) TYPE(*CHAR) LEN(10)
The DCL command is used in CLP programs to declare the program variables.
DCLF FILE(FLATFILE1) OPNID(FL1)
This DCLF command is used to declare file named FLATFILE1 in cl program with open identifier FL1.
READ: RCVF OPNID(FL1)
The Receive File (RCVF) command is used to receive data from a database file. Here, Open File Identifier (OPNID) parameter to give each file its own unique id. I just use FL1.
MONMSG MSGID(CPF0864) EXEC(GOTO CMDLBL(END))
Here, the MONMSG command follows the Receive File (RCVF) command and, therefore, is only monitoring for messages sent by the RCVF command. this example specifies MSGID(CPF0864), the MONMSG monitors for this condition. When it receives the message, the GOTO CMDLBL(END) command is run. Please note that CPF0864 denotes End of file reach.
CHGVAR VAR(&VAR1) VALUE(&FL1_FLATFILE1)
&VAR1 is set to the value of the variable &FL1_FLATFILE1
CHGVAR VAR(&VAR2) VALUE(%SST(&FL1_FLATFILE1 1 10))
&VAR2 is set to the value of the variable &FL1_FLATFILE1 for 1st 10 positions.
CHGVAR VAR(&VAR3) VALUE(%SST(&FL1_FLATFILE1 11 10))
&VAR3 is set to the value of the variable &FL1_FLATFILE1 for 10 positions start from 11th position.
Please note that, FL1_ is specified for each field of a file with CHGVAR command just because we used open id FL1_ with file FLATFILE1 during declare and open of the file.