02
Sat, Nov
2 New Articles

Practical RPG: Processing Stream Files, Part 2

RPG
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

In part 1, we processed a directory. In part 2, we process one file in that directory.

Stream files are not database files.

While that statement is obvious to programmers, it's not always clear to the greater community. The end users, the folks whose jobs we are supposed to be supporting, use various forms of stream files to store their data, and they don't understand why we can't for example just "use this spreadsheet" as part of our application. And while that's an interesting philosophical discussion, as programmers we sometimes have to simply get things done, and that in turn means taking whatever data the user sent us. I've spent a lot of time over the years importing data primarily from Exceland more specifically from comma-delimited files. Two techniques exist: CPYFRMIMPF and parsing the data in RPG. CPYFRMIMPF is a completely different animal that perhaps can be covered another day. Today, I just want to talk about parsing a stream file.

Why DIY?

Why do it yourself? The primary benefit is that you have complete control over the processing. Though convenient, CPYFRMIMPF limits you. As an example, you can't use CPYFRMIMPF if your stream file has varying formats (such as header and detail lines). Or let's say you want to process the file differently based on something in one of the records; with CPYFRMMIPF, you would have to copy all the records to a temporary file and then process that file. That's not necessarily a bad thing; I do exactly that in many of the import subsystems I've written over the years. But let's say you want to use only a few records in a large import file. In that case, you'd have to extract all the records into the temporary file even though you're only using a few.

So today's example is going to focus on reading the stream file yourself. One note: Since this is defined to be a comma-delimited file, I can treat it as a standard human-readable text file. Under other circumstances, you might receive binary data, which requires a completely different access technique. There are actually routines that allow you to directly access an Excel file, as an example. They're in Java and well outside the scope of this article, but I thought you should know.

Processing a Stream File

Stream file contents are accessed using APIs similar to the ones I introduced in the previous article on processing directories. Let's take a look at the prototypes for the APIs I'll be calling in this program.

     dcl-pr IFS_fopen pointer extproc('_C_IFS_fopen');

      file pointer value options(*string);

      mode pointer value options(*string);

     end-pr;

     dcl-pr IFS_fclose extproc('_C_IFS_fclose');

      fd pointer value;

     end-pr;

     dcl-pr IFS_fgets pointer extproc('_C_IFS_fgets');

      pbuf pointer value;

      size uns(10) value;

      fd pointer value;

     end-pr;

They're quite straightforward: open, close, and get. The open and close are very simple. IFS_open takes a file name and an access mode (we'll be using read mode) and returns a file handle. Pass that handle to IFS_close and the file is closed. Of course, opening and closing a file doesn't do you much good without at least one intervening read; that's the job of the get routine IFS_fgets. I also define a few variables.

     dcl-s fp pointer;

     dcl-s sp pointer;

     dcl-s buf varchar(2000);

I use two pointers and a buffer. Note that the buffer is type varchar. I do that so that I don't have to constantly keep track of the length of the data that I've read in, but it does make for a rather strange bit of code later on. But let's start walking through the logic.


       // Open stream file

    fp = IFS_fopen( wFile: 'r');

   if fp = *null;

      SetError('01':%str(strerror(errno)));

      return;

   endif;

This is very simple code. The variable wFile contains a fully qualified file name, and IFS_fopen attempts to open it. The mode is "r", which indicates read-only open. If the file doesn't exist, you'll get an error. The SetError routine is just a placeholder to show you how you might signal an error to the caller. How you handle this sort of fatal error depends very much upon the application. You may also notice the use of %str. When you're using the C APIs, you tend to use that a lot. It converts between traditional RPG character variables and the null-terminated strings that C uses. In this case, the routines strerror and errno combine to return a human-readable error message, but that message is null-terminated. We need %str to use it in our RPG program. Assuming, though, that the open is successful, the variable fp (which has been defined as type pointer) will contain a handle which you can then use for any of the other file-based APIs. And we do that immediately by trying to get the first line.

   // Read in the first line

    sp = IFS_fgets(%addr(buf:*data): %size(buf): fp);

   if sp = *null;

      SetError('02':%str(strerror(errno)));

      return;

   endif;

    buf = %str(sp);

As I said, the IFS_fgets function isn't exactly intuitive, especially to we RPG programmers who haven't traditionally done a lot of pointer-based programming. I have to pass IFS_fgets the address of the buffer and the size of the buffer, along with the file handle that we got from the IFS_fopen API in the previous section of code. If the routine is successful, it returns the same pointer I passed in. If it's not successful, it returns null (that's the test that you see immediately following the API call). But the really confusing part is the next line, where I convert the null-terminated value returned from IFS_fgets into a regular RPG string, which I then place in the variable buf. But you might be asking yourself, why do that? Isn't the data already in buf? Well, yes, it is, but buf is type varchar, and the IFS_gets didn't set the length. Now, you might think I could just set the length of the variable, perhaps by scanning the string for the terminating null:

   %len(buf)= %scan(x'00':buf) - 1;

That looks good, but I found something out through some painful trial and error. It turns out that the compiler really, really wants to be helpful, and if you set the length of a variable, it will fill the variable with blanks. So all that nice data that you just read into the buffer is overwritten with blanks, which certainly defeats the purpose. So I don't do that; instead, I use the previous line, in which I basically overwrite the buffer with itself. It's counter-intuitive, but it works perfectly. So now for the rest of the code.

   // Parse the buffer and process it

    Parse(buf);

   // Close the file

    IFS_fclose(fp);

       return;

And that's all it takes. Now obviously this particular code only processes the first line of the file. That might be enough, especially in an inbound router. The router may read the file, use some logic to identify the transaction type, and then send it on to another program. But this is exactly the scenario where you might need your own parser rather than a generic CPYFRMIMPF.

Where to Go from Here

So clearly this is a very simple application. All of the work will be done in the Parse routine, which I don't even show here. If I get a call for it, I can probably do another article on parsing, but for now this should give you enough of a start on IFS processing to give you some ideas of where it could be helpful in your environment. I've had great success using this to allow users to upload their own data to the system (after running it through validation, of course). Use this basic design to have some fun with the IFS and see what you can come up with.

Joe Pluta

Joe Pluta is the founder and chief architect of Pluta Brothers Design, Inc. He has been extending the IBM midrange since the days of the IBM System/3. Joe uses WebSphere extensively, especially as the base for PSC/400, the only product that can move your legacy systems to the Web using simple green-screen commands. He has written several books, including Developing Web 2.0 Applications with EGL for IBM i, E-Deployment: The Fastest Path to the Web, Eclipse: Step by Step, and WDSC: Step by Step. Joe performs onsite mentoring and speaks at user groups around the country. You can reach him at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Joe Pluta available now on the MC Press Bookstore.

Developing Web 2.0 Applications with EGL for IBM i Developing Web 2.0 Applications with EGL for IBM i
Joe Pluta introduces you to EGL Rich UI and IBM’s Rational Developer for the IBM i platform.
List Price $39.95

Now On Sale

WDSC: Step by Step WDSC: Step by Step
Discover incredibly powerful WDSC with this easy-to-understand yet thorough introduction.
List Price $74.95

Now On Sale

Eclipse: Step by Step Eclipse: Step by Step
Quickly get up to speed and productivity using Eclipse.
List Price $59.00

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: