05
Sat, Oct
2 New Articles

Cool Things: Read dBASE Files Easily!

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

This simple service program makes dBASE file access simple.

Written by Mike Faust

dBASE has been around since the late 1970s/early 1980s. It was the first widely used relational database for PCs. I recently had a need to import data into the System i from the U.S. Census Bureau's Tiger database, which stores address data for all of the United States, including state, county, and city. The Tiger database is made up of multiple dBASE format files, so I needed to create a means by which I could read the data directly from the System i. In this tip, we'll take a look at a simple service program that gives you the ability to do sequential data reads from a dBASE file.

dBASE Table File Format

The dBASE file format is actually relatively easy to read. Tables contain header information that describes the table itself, along with a field descriptor array that defines all of the fields in the file. The data immediately follows the header information and is broken apart based on the field descriptors. Information on the dBASE file layout can be found on the dBASE Web site.

 

The field descriptor array contains one element for each field in the table.  These values describe the field names and the type of data contained in the field. You can determine the end of the field descriptor array by the line field character (hex 0D).

 

Since all of this information is stored sequentially within the file, it's easy enough to create a service program that reads the file from the IFS and returns the information that is stored in the table file.

The Service Program

To allow for easy access to dBASE table files, I've created a simple service program. The source for this service program can be found here. The source for the service program contains three members.

 

  • dBASEf—This member contains the code for all of the subprocedures inside of this service program.
  • dBASEfbnd—The binder language source for the service program is found in this source member.
  • dBASEprc—The prototypes for each of the subprocedures are stored in this source member. This can then be used with a /copy in RPGLE programs that are bound to the service program.

 

The process of compiling the service program involves first creating the RPGLE module using the CRTRPGMOD command:

 

CRTRPGMOD   MODULE(MYLIB/DBASEF)
            SRCFILE(MYLIB/QRPGLESRC)  SRCMBR(DBASEF)

 

Next, the service program is created using the CRTSRVPGM command:

 

CRTSRVPGM   SRVPGM(DBASEF) EXPORT(*SRCFILE) SRCFILE(MYLIB/QRPGLESRC) SRCMBR(DBASEFBND)

 

This service program contains five sub-procedures:

 

  • opendBASEFile(dBASE_stream_file):  This subprocedure performs several functions. First, it creates a pointer to space allocated in memory to store the data structure that holds the information on the dBASE table being opened. Next, it opens the actual dBASE stream file on the IFS. Then, it uses the previously defined header data structures to determine various details about the dBASE table, including details on the columns in the table. All of this data is stored in the data structure that is based on the pointer we allocated at the beginning of the subprocedure. This allows us to make this information available to the calling program without passing large volumes of data back and forth.

 

  • readdBASEFile(file_header_pointer):  This subprocedure loads data from the defined dBASE file into a structure that can then be used to retrieve the individual data fields. It accepts a single parameter that represents the pointer to the header for the dBASE file containing the record to be read. Then, it returns a pointer parameter that identifies the location in memory where the record data is stored. The subprocedure simply reads the next record sequentially and stores the entire record as a  string in memory.

 

  • getdBASEField(file_header_pointer: record_pointer: field_number):  This subprocedure returns a data structure that contains data from a specified field in the  requested record based on the field's ordinal position in the record.

 

  • getdBASEFieldByName(file_header_pointer: record_pointer: field_name):  This subprocedure returns a data structure that contains data from a specified field in the requested record based on the field name.

 

  • closedBASEFile(file_header_pointer):  This subprocedure closes the streamed file associated with the file header pointer and then sets the pointer to null.

 

These subprocedures use a set of data structures to store data associated with the file header and field data. Below are descriptions of these data structures.

 

Table 1: dbfHeader Data Structure

Field Name

Data Type/Length

Description

Version

Numeric 1,0

The numeric value used to determine the version of the dBASE file

LastUpdated

Date

The date the dBASE file was last updated

RecordCount

Integer

The number of records in the dBASE file

BytesPerRecord

Integer

The length in bytes of each data record

FieldCount

Integer

The number of fields in the dBASE file

Fields

Array/Data Strucutre

An array containing a field data structure defining each field in the dBASE file

CurrentRecord

Integer

The relative record number for the current record based on the last readdBASEFile

FileDescriptor

Integer

The return value from the IFS open API, used to access the streamed file

 

 

 

Table 2: Field Description Data Structure

Field Name

Data Type/Length

Description

Name

Character 11

The name of the field

Type

Character 1

The field type (based on the dBASE field types described earlier)

Length

Integer

The total length of the field

Decimals

Integer

The number of decimal places (for numeric fields only)

Offset

Integer

The starting position for the field in the record

 

 

Table 3: Data Structure to Return Field Data

Field Name

Data Type/Length

Description

Type

Character 1

The name of the field

String

Character 32767

A string representation of the value

Number

Numeric 31,9

A numeric representation of the value (valid only for numeric fields)

Date

Date

For date fields only, the date as a date type field

 

The data structure in Table 1 is generated by the opendBASEFile subprocedure. Within that data structure, multiple copies of the field description data structure shown in Table 2 are generated. That structure contains all of the information for each field in the table. The data structure described in Table 3 shows the data returned by the getdBASEField and getdBASEFieldByName subprocedures.

Sample Program

To see how to use the dBASEf service program, take a look at the TESTDBF RPGLE program shown below:

 

//********************************************************************

      // Purpose: Test Program

      //********************************************************************

 

     h dftactgrp(*no)

     h option(*nodebugio:*srcstmt:*seclvl)

     h bnddir('TESTDIR')

 

      /copy qrpglesrc,DBASEFPRC

     dtestdbf          pr

     d prmdBASEfile                 500a

     dtestdbf          pi

     d prmdBASEfile                 500a

 

     d wkDSHeader      ds                  likeDs(dbfHeader) based(ptrHeader)

     d wkRecordStr     s          65535a   based(ptrRecord)

     d wkRecordCount   s              5  0

     d wkIndex         s              3  0

     d wkField         ds                  likeds(fieldData)

     d wkStr           s          32766a

 

      /free

 

        ptrHeader = openDBaseFile(prmDBaseFile);

 

        wkRecordCount = 0;

 

        ptrRecord = readDBASEFile(ptrHeader);

        dow ptrRecord <> *null and wkRecordCount < wkDSHeader.RecordCount;

           wkRecordCount += 1;

           wkField = getDBaseField(ptrHeader: ptrRecord: 1);

           wkStr = wkField.String;

           dsply %subst(wkStr: 1: 50);

           ptrRecord = readDBASEFile(ptrHeader);

        enddo;

 

        closeDBaseFile(ptrHeader);

        *INLR = *on;

        return;

 

      /end-free

 

This sample program accepts a single parameter that contains the path to the dBASE file to be opened. It also assumes that the DBASEF service program has already been added to a binding directory named TESTDIR. This program simply opens the specified dBASE file using the opendBASEFile subprocedure, reads each record, and then displays the contents of the first field in that record using the getdBASEField subprocedure. Note that we could just as easily use the getdBASEFieldByName subprocedure, using a field name to retrieve the same information. Finally, the program closes the dBASE file using the closedBASEFile subprocedure.

What It Won't Do

This simple service program does give powerful functionality, but what it won't allow you to do is update a dBASE file, nor will it allow you to read by keyed field or indexes. That being said, this service program does give you an easy way to access dBASE files inside of an ILE RPG program.

Mike Faust

Mike Faust is a senior consultant/analyst for Retail Technologies Corporation in Orlando, Florida. Mike is also the author of the books Active Server Pages Primer, The iSeries and AS/400 Programmer's Guide to Cool Things, JavaScript for the Business Developer, and SQL Built-in Functions and Stored Procedures. You can contact Mike at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Mike Faust available now on the MC Press Bookstore.

Active Server Pages Primer Active Server Pages Primer
Learn how to make the most of ASP while creating a fully functional ASP "shopping cart" application.
List Price $79.00

Now On Sale

JavaScript for the Business Developer JavaScript for the Business Developer
Learn how JavaScript can help you create dynamic business applications with Web browser interfaces.
List Price $44.95

Now On Sale

SQL Built-in Functions and Stored Procedures SQL Built-in Functions and Stored Procedures
Unleash the full power of SQL with these highly useful tools.
List Price $49.95

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: