RPGLE example reading from Db2 FLATFILE into Data Structure

Here is an example of an IBM RPGLE program that reads a file and loads the data into a Data Structure:

**free
//
// RPGLE Program to read a flat DB2 File
// and load into a data structure
//

ctl-opt dftactgrp(*no) actgrp('NICKLITTEN');

dcl-f flatfile usage(*Input) RENAME(FLATFILE:RECFMT) PREFIX(#) usropn;

// here we define a data structure with the fields we want to define
// then we overlay a 'pointer' over that array in memory space
dcl-s pointer_ds pointer ;
dcl-ds ds_data qualified based(pointer_ds);
field1 char(10);
field2 char(20);
field3 int(10);
end-ds;

open flatfile;

read flatfile;
dow not %eof(flatfile);

// now we populate the 'memory space' of the array with the
// 'memory space' of the file data called '#flatfile'
pointer_ds = %addr(#flatfile);

// The pointer voerlays the ds_data data structure
// now we could do something with the granular field values
// ds_data.field1
// ds_data.field2
// ds_data.field3

read flatfile;
enddo;

close flatfile;

*inlr = *on;
return;

Note that the **free at the beginning of the code indicates that this is a free-format RPGLE program, which provides a more modern and readable syntax compared to the traditional fixed-format RPGLE.

The program reads a file named flatfile from the library list of the job that is calling the program. We have to rename the record format (which is also called flatfile) and we prefix the field name (which is also called flatfile) with an # symbol.

 The flat file was created with:

crtpf nicklitten/flatfile rcdlen(500)

 We have to jump through a couple of small hoops to make this work with modern RPG. Modern RPGLE is much more strict with memory management than the old RPG. The old RPG let us use the MOVEA operation code, which would simply move an entire array in or out of a field. 

But with modern RPG, it's much more regimented. 

So, we declare pointer that overlays our data structure.

Then in our code, we just populate that pointer, with the address of the variable that we read in #flatfile. This literally says, take the memory space of this variable and put it into the memory space of this variable; A data structure and that's it!

Bada Bing, few lines of code, we managed to read an entire file, everything in that record format, straight into a data structure. And now we just have to worry that all the fields are in the right places. 

I like this technique.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
>