Let's start with a flat file called 'FLATFILE' (you never could of guess that right?)
A flat file, characterized by its lack of DDS and defined record length, maintains a uniform record format and field name, with the field size matching the record length. This presents a unique challenge for our RPG program, which involves renaming the format to avoid conflicts with the file name. This example RPG code will retrieve data from a flat file into a variable within an RPGLE program.
Let's start with a good old fashioned RPG Column Based example
Legacy RPG Example
HOption(*NoDebugio)
FFLATFILE IF E DISK RENAME(FLATFILE:RECFMT)
F PREFIX(#)
D LocalVariable S 500A
C *START SETLL FLATFILE
C READ FLATFILE
C DOW Not %EOF(FlatFile)
C EVAL LocalVariable = #FlatFile
C READ FLATFILE
C ENDDO
C EVAL *INLR = *ON
*shudder*
Let's quickly convert this same code into modern RPG to make it more readable.
Modern RPG Example
Ctl-Opt Debug(*Yes) Option(*NoDebugio);
Dcl-F FLATFILE Usage(*Input) RENAME(FLATFILE:RECFMT) PREFIX(#);
Dcl-S LocalVariable Char(500);
SETLL *START FLATFILE;
READ FLATFILE;
DOW Not %EOF(FlatFile);
LocalVariable = #FlatFile;
READ FLATFILE;
ENDDO;
*INLR = *ON;
What is the code doing?
The control option line tells That we want to use debug when we're running this program.
The file is declared with a dcl-F statement. It says it's called flatfile. It's used for input, and then we're renaming the internal record format from flatfile to recfmt. The prefix of #flatfile says that when it reads the field in from the file, which will also be called flat file, to call it #flatfile.
This way we separate the names of the file. The record format and the field within the file because they were the same.
Then we declare a working variable which I've just called local variable. And that's it.
Let's get into the mainline processing for this code.
The SETLL says, position the pointer at the start of the file.
The READ, Reads the file and populates that field called flatfile. But in this case, it would be called hash flat file because we prefixed it.
Assuming it found the first row, it will go into the loop that says, do while not end of file. Now with the data from that first row, it will store it in the variable called local variable. This is where you would add business logic that says, do something with local variable. Write it somewhere. Print it or something like that.
Then we carry on to the next read statement, which would read row 2. If it existed, and assuming it was found, the End Loop would take you back to the top of the loop, and it would load row 2 into local variable. This would keep on going until that read flat file hits end of file. In which case it would drop out of the loop.
Then *INLR being turned on, as all RPG programmers know, indicates it's time to end the program.
And there you have it.